tickle/modules/utils/memoize.mjs

30 lines
686 B
JavaScript

//@ts-check
/**
* Caches the result of a function.
* The cache is available as `.cache` in case there's a need to clear anything.
* @template {(...args: any[]) => any} T
* @param {T} functionToMemoize
* @returns
*/
export const memoize = (functionToMemoize) => {
/** @type {Map<Parameters<T>[0], ReturnType<T>>} */
const cache = new Map()
/**
*
* @param {Parameters<T>} args
* @returns {ReturnType<T>}
*/
const memoized = (...args) => {
const key = args[0]
if(!cache.has(key)){
cache.set(key, functionToMemoize(...args))
}
//@ts-ignore
return cache.get(key)
}
memoized.map = cache
return memoized
}
export default memoize