tickle/modules/utils/memoize.mjs

34 lines
960 B
JavaScript
Raw Normal View History

2023-05-18 21:33:33 +00:00
//@ts-check
2023-06-07 16:51:18 +00:00
const pickFirstArg = (fst, ..._none) => JSON.stringify(fst)
2023-05-18 21:33:33 +00:00
/**
* Caches the result of a function.
* The cache is available as `.cache` in case there's a need to clear anything.
2023-06-07 16:51:18 +00:00
* Uses the first parameter as a key by default, you can change this behavior by passing a custom
* hash function.
2023-05-18 21:33:33 +00:00
* @template {(...args: any[]) => any} T
* @param {T} functionToMemoize
2023-06-07 16:51:18 +00:00
* @param {(...args: Parameters<T>) => string|number} [hashFunction]
2023-05-18 21:33:33 +00:00
* @returns
*/
2023-06-07 16:51:18 +00:00
export const memoize = (functionToMemoize, hashFunction = pickFirstArg) => {
/** @type {Map<string|number, ReturnType<T>>} */
2023-05-18 21:33:33 +00:00
const cache = new Map()
/**
*
* @param {Parameters<T>} args
* @returns {ReturnType<T>}
*/
const memoized = (...args) => {
2023-06-07 16:51:18 +00:00
const key = hashFunction(...args)
2023-05-18 21:33:33 +00:00
if(!cache.has(key)){
cache.set(key, functionToMemoize(...args))
}
return cache.get(key)
}
2023-06-07 16:51:18 +00:00
return Object.assign(memoized, { cache })
2023-05-18 21:33:33 +00:00
}
export default memoize