MCPcopy
hub / github.com/josdejong/mathjs / memoize

Function memoize

src/utils/function.js:20–48  ·  view source on GitHub ↗
(fn, { hasher, limit } = {})

Source from the content-addressed store, hash-verified

18 * @return {function} Returns the memoized function
19 */
20export function memoize (fn, { hasher, limit } = {}) {
21 limit = limit == null ? Number.POSITIVE_INFINITY : limit
22 hasher = hasher == null ? JSON.stringify : hasher
23
24 return function memoize () {
25 if (typeof memoize.cache !== 'object') {
26 memoize.cache = {
27 values: new Map(),
28 lru: lruQueue(limit || Number.POSITIVE_INFINITY)
29 }
30 }
31 const args = []
32 for (let i = 0; i < arguments.length; i++) {
33 args[i] = arguments[i]
34 }
35 const hash = hasher(args)
36
37 if (memoize.cache.values.has(hash)) {
38 memoize.cache.lru.hit(hash)
39 return memoize.cache.values.get(hash)
40 }
41
42 const newVal = fn.apply(fn, args)
43 memoize.cache.values.set(hash, newVal)
44 memoize.cache.values.delete(memoize.cache.lru.hit(hash))
45
46 return newVal
47 }
48}
49
50/**
51 * Memoize a given function by caching all results and the arguments,

Callers 3

function.test.jsFile · 0.90
constants.jsFile · 0.90
Unit.jsFile · 0.90

Calls 6

lruQueueFunction · 0.90
hasherFunction · 0.85
hasMethod · 0.65
getMethod · 0.65
setMethod · 0.65
deleteMethod · 0.45

Tested by

no test coverage detected

Used in the wild real call sites across dependent graphs

searching dependent graphs…