Skip to main content
Deno 2 is finally here 🎉️
Learn more
Module

x/froebel/function.ts>memoize

A strictly typed utility library.
Go to Latest
variable memoize
import { memoize } from "https://deno.land/x/froebel@v0.18.0/function.ts";

Returns a copy of fun that remembers its result for any given arguments and only invokes fun for unknown arguments.

The cache key is computed using the key function. The default key function simply stringifies the arguments.

If limit is specified, only the limit-last entries are kept in cache.

The function's cache is available at memoized.cache.

If opt.weak is true, non-primitive cache keys are stored in a WeakMap. This behavior might for example be useful if you want to memoize some calculation including a DOM Node without holding on to a reference of that node. Using weak keys prohibits setting a limit.

Examples

Example 1

const expensiveCalculation = (a: number, b: number) => {
  console.log(`calculate ${a} + ${b}`)
  return a + b
}
const calc = memoize(expensiveCalculation)

console.log( calc(1, 2) )
// calculate 1 + 2
// 3
console.log( calc(20, 5) )
// calculate 20 + 5
// 25
console.log( calc(20, 5) )
// 25
console.log( calc(1, 2) )
// 3

calc.cache.clear()
console.log( calc(1, 2) )
// calculate 1 + 2
// 3

Example 2

const logIfDifferent = memoize(
  (msg: string) => console.log(msg),
  {
    limit: 1,
    key: msg => msg
  }
)

logIfDifferent('a')
logIfDifferent('a')
logIfDifferent('b')
logIfDifferent('a')

// a
// b
// a

type

<T extends λ, K = string, W extends boolean = false>(fun: T, opt?: { key?: (...args: Parameters<T>) => K; limit?: number; weak?: W; }) => T & { cache: W extends false ? Map<K, ReturnType<T>> : Cache<K, ReturnType<T>>; }