Hyperlinkv0.8.0-beta.28

Function

Function.memoizefunctioneffect/Function.ts:1405
<A extends object, O>(f: (a: A) => O): (ast: A) => O

Creates a memoized function whose input is an object, caching results by object identity.

When to use

Use to reuse the result of a synchronous computation whose output is stable for a given object reference.

Details

Each memoized wrapper owns a private WeakMap keyed by object identity. Cached undefined results are still returned because the cache is checked with WeakMap.has.

Gotchas

Structurally equal objects do not share cache entries. If the same object is mutated after its first call, later calls still return the cached result for that reference.

caching
export function memoize<A extends object, O>(f: (a: A) => O): (ast: A) => O {
  const cache = new WeakMap<object, O>()
  return (a) => {
    if (cache.has(a)) {
      return cache.get(a)!
    }
    const result = f(a)
    cache.set(a, result)
    return result
  }
}
Referenced by 3 symbols