demo · v143
Memoize cache
The original TC39 proposal motivation: turn the four-line "check, compute, set" memoization dance into one call. We memoize a pretend-slow Fibonacci with both styles side-by-side and count cache hits vs misses.
compute fib(n)
old: has + set dance
hits: 0
misses: 0
last call: —
new: getOrInsertComputed
hits: 0
misses: 0
last call: —
call log
the call
// Before: the four-line dance
function memoOld(n) {
if (cache.has(n)) return cache.get(n);
const v = compute(n);
cache.set(n, v);
return v;
}
// After: one line, factory only runs on miss
function memoNew(n) {
return cache.getOrInsertComputed(n, compute);
}
why this angle
This is the canonical TC39 motivating example. The "check + compute + set" pattern is so common it inspired the whole proposal. Crucially, getOrInsertComputed only invokes the factory on a miss, so expensive computation is skipped on a hit — unlike map.get(k) ?? map.set(k, compute()).get(k) hacks that always run the right-hand side.
see also
- Upsert — feature index
- Map.getOrInsert(Computed) demo
- TC39 proposal
- ChromeStatus entry