frontpage.
newsnewestaskshowjobs

Made with ♥ by @iamnishanth

Open Source @Github

Open in hackernews

JavaScript helper function for you to use

4•EGreg•2h ago
Got a function that fetches some values asynchronously from somewhere? Consider wrapping it in this and making it a super-function.

Here is what it does for all the functions you wrap with it. In my experience, these are very helpful and also gives you a place you can even hook into and add more later (such as handling batching transparencly, etc):

Memoizes async getters: Call a function with the same arguments and it returns the cached result instead of recomputing.

Handles in-flight deduping: If multiple parts of your app call the same getter while it's still working, only one request is sent. The rest wait on the same promise.

Throttles concurrency: You can limit how many calls to your getter run in parallel. Useful for APIs, disk I/O, or anything rate-sensitive.

Supports custom caching backends: Pass any object with get, set, delete, and has. Works with Map, LRU, or your own cache logic.

Optional LRU eviction: If you pass a plain Map, it upgrades it to an LRU with a max size. Least recently used items are evicted when full.

Handles callbacks and Promises: Wraps traditional callback-style async functions, but gives you a modern Promise-based interface.

Smart-ish keying: Builds a cache key by stringifying non-function arguments. Works well for most everyday use cases.

Supports manual eviction: Call getter.forget(...args) to remove specific entries or getter.force(...args) to bypass the cache for one call.

Allows custom preparation logic: You can pass a prepare() function to clone or process cached results before using them.

  function createGetter(fn, {
    cache = new Map(),
    cacheSize = 100, // Used only if cache is a Map
    throttleSize = Infinity,
    prepare,
    callbackIndex,
    resolveWithFirstArgument = false
  } = {}) {
    const inFlight = new Map();
    let activeCount = 0;
    const queue = [];
  
    // Wrap Map in a simple LRU if needed
    if (cache instanceof Map) {
      const rawMap = cache;
      const lru = new Map();
  
      cache = {
        get(key) {
          if (!rawMap.has(key)) return undefined;
          const value = rawMap.get(key);
          lru.delete(key);
          lru.set(key, true); // Mark as most recently used
          return value;
        },
        set(key, value) {
          rawMap.set(key, value);
          lru.set(key, true);
          if (rawMap.size > cacheSize) {
            const oldest = lru.keys().next().value;
            rawMap.delete(oldest);
            lru.delete(oldest);
          }
        },
        delete(key) {
          rawMap.delete(key);
          lru.delete(key);
        },
        has(key) {
          return rawMap.has(key);
        }
      };
    }
  
    function makeKey(args) {
      return JSON.stringify(args.map(arg => (typeof arg === 'function' ? 'ƒ' : arg)));
    }
  
    function execute(context, args, key, resolve, reject) {
      const callback = (err, result) => {
        if (err) return reject(err);
        cache.set(key, [context, arguments]);
        if (prepare) prepare.call(null, context, arguments);
        resolve(resolveWithFirstArgument && context !== undefined ? context : result);
        processNext();
      };
  
      if (callbackIndex != null) args.splice(callbackIndex, 0, callback);
      else args.push(callback);
  
      if (fn.apply(context, args) === false) {
        cache.delete(key); // opt-out of cache
      }
    }
  
    function processNext() {
      activeCount--;
      if (queue.length && activeCount < throttleSize) {
        const next = queue.shift();
        activeCount++;
        execute(...next);
      }
    }
  
    const getter = function (...args) {
      return new Promise((resolve, reject) => {
        const context = this;
        const key = makeKey(args);
  
        if (cache.has(key)) {
          const [cachedContext, cachedArgs] = cache.get(key);
          if (prepare) prepare.call(null, cachedContext, cachedArgs);
          return resolve(resolveWithFirstArgument && cachedContext !== undefined ? cachedContext : cachedArgs[1]);
        }
  
        if (inFlight.has(key)) {
          return inFlight.get(key).then(resolve, reject);
        }
  
        const promise = new Promise((res, rej) => {
          if (activeCount < throttleSize) {
            activeCount++;
            execute(context, args.slice(), key, res, rej);
          } else {
            queue.push([context, args.slice(), key, res, rej]);
          }
        });
  
        inFlight.set(key, promise);
        promise.finally(() => {
          inFlight.delete(key);
        });
  
        promise.then(resolve, reject);
      });
    };
  
    getter.forget = (...args) => {
      const key = makeKey(args);
      inFlight.delete(key);
      return cache.delete(key);
    };
  
    getter.force = function (...args) {
      getter.forget(...args);
      return getter.apply(this, args);
    };
  
    return getter;
  }

What is a micro-retirement? Inside the latest Gen Z trend

https://www.fastcompany.com/91357784/what-is-a-micro-retirement-inside-the-latest-gen-z-trend
1•yladiz•3m ago•1 comments

Paper: Disambiguation-Centric Finetuning Makes Tool-Calling LLMs More Realistic

https://arxiv.org/abs/2507.03336
1•ashutosh1919•5m ago•0 comments

Who Needs Privacy?

https://behind4the4curtain.substack.com/
1•totogale•9m ago•0 comments

How to Delete Bad Google Maps Reviews

https://blog.mbirth.uk/2025/07/09/how-to-delete-bad-google-maps-reviews.html
1•mbirth•9m ago•0 comments

Whooo's there? James Webb Telescope spots 'Cosmic Owl,' super-rare structure

https://www.livescience.com/space/astronomy/whooos-there-james-webb-telescope-spots-cosmic-owl-super-rare-structure-formed-from-colliding-ring-galaxies
1•Bluestein•10m ago•0 comments

Elon Musk's Grok Chatbot Goes Full Nazi, Calls Itself 'MechaHitler'

https://www.rollingstone.com/culture/culture-news/elon-musk-grok-chatbot-antisemitic-posts-1235381165/
5•pulisse•11m ago•0 comments

In 2003, a U.S. Air Force F-16 and a U.S. Army Missile Battery Fought Each Other

https://daxe.substack.com/p/in-2003-a-us-air-force-f-16-and-a
1•vinnyglennon•12m ago•0 comments

OpenAI Hires 4 High-Ranking Engineers from Competitors

https://www.wired.com/story/openai-new-hires-scaling/
2•kirubakaran•14m ago•0 comments

IRS says churches can now endorse political candidates

https://www.npr.org/2025/07/08/nx-s1-5460886/irs-now-says-pastors-can-endorse-political-candidates
4•geox•14m ago•1 comments

Towards Human-Like AI: A Review of Anthropomorphic Computing

https://www.mdpi.com/2227-7390/13/13/2087
1•PaulHoule•16m ago•0 comments

Why is RL important, especially for LLMs?

https://opipe.notion.site/why-is-rl-important-especially-for-llms
1•Arctic_fly•17m ago•1 comments

Debian Conference 2025 Schedule

https://debconf25.debconf.org/schedule/
1•pabs3•18m ago•0 comments

Reliable Distributed Applications

https://docs.temporal.io/evaluate/why-temporal
1•skor•19m ago•0 comments

O que é uma Plataforma White-Label

https://comofidelizarclientes.com.br/o-que-e-uma-plataforma-white-label/
1•edtho•20m ago•0 comments

She Wanted to Save the World from A.I

https://www.nytimes.com/2025/07/06/business/ziz-lasota-zizians-rationalists.html
1•CharlesW•22m ago•0 comments

Programmatic SEO: The #1 Growth Hack

https://guptadeepak.com/programmatic-seo-the-1-growth-hack-that-transforms-businesses-from-content-creators-to-market-leaders/
1•guptadeepak•23m ago•1 comments

Show HN: Necto – A Unified AI Workspace

https://necto.co
1•fraco•25m ago•0 comments

In macOS Tahoe, Things Are Indeed Dire for FireWire

https://512pixels.net/2025/07/tahoe-no-firewire/
3•CharlesW•25m ago•1 comments

MIPS and GlobalFoundries: Powering the Next Wave of Physical AI

https://mips.com/blog/mips-and-globalfoundries-powering-the-next-wave-of-physical-ai/
1•pabs3•28m ago•0 comments

Grok praises Hitler, gives credit to Musk for removing "woke filters"

https://arstechnica.com/tech-policy/2025/07/grok-praises-hitler-gives-credit-to-musk-for-removing-woke-filters/
7•arunbahl•28m ago•0 comments

Seeing Networks in New York City

https://web.archive.org/web/20170922171552/http://seeingnetworks.in/nyc/
1•sandwichsphinx•31m ago•0 comments

Jeff Williams, 62, Is Retiring as Apple's COO

https://daringfireball.net/2025/07/jeff_williams_is_retiring_as_coo
1•Bogdanp•36m ago•0 comments

A Comprehensive Proposal Overviewing Blocks, Nested Functions, and Lambdas for C

https://thephd.dev/_vendor/future_cxx/papers/C%20-%20Functional%20Functions.html
2•matt_d•37m ago•0 comments

CPU stuck at 0.80Ghz, Fixed by removing keyboard screw

https://www.dell.com/community/en/conversations/latitude/cpu-core-speed-stuck-at-080ghz-latitude-e7440/647f79dcf4ccf8a8de805bd2?page=2
14•ViscountPenguin•37m ago•3 comments

Jeff Williams to be replaced as Apple COO

https://sixcolors.com/link/2025/07/jeff-williams-to-be-replaced-as-apple-coo/
1•robenkleene•38m ago•1 comments

Amazon Bedrock introduces API keys for streamlined development

https://aws.amazon.com/about-aws/whats-new/2025/07/amazon-bedrock-api-keys-for-streamlined-development/
1•rectalogic•38m ago•0 comments

Show HN: Visual Editor for Cursor

https://shuffle.dev/cursor
2•kemyd•48m ago•0 comments

Collabora Advances Rust-for-Linux with New Tyr DRM Driver for Mali GPUs

https://linuxgizmos.com/collabora-advances-rust-for-linux-with-new-tyr-drm-driver-for-mali-gpus/
4•chsum•53m ago•0 comments

LLM Failures

http://funcall.blogspot.com/2025/07/llm-failures.html
1•bikenaga•53m ago•0 comments

Founder mode will become the new Manager mode [video]

https://www.youtube.com/watch?v=sOeF59oIT7k
1•stalco•54m ago•1 comments