tamda
Version:
Practical functional programming library for TypeScript
18 lines • 719 B
JavaScript
/**
* Creates a function that caches the result of function `fn` for each set of arguments,
* avoiding computation when a matching set is invoked again.
* @param fn Function to memoize.
*/
export function memoize(fn) {
const cache = new Map();
return ((...args) => navigate(cache, fn, args));
}
const resultKey = '~result~';
function navigate(cache, fn, args) {
const leaf = args.reduce((branch, arg) => getOrSet(branch, arg, () => new Map()), cache);
return getOrSet(leaf, resultKey, () => fn.apply(undefined, args));
}
function getOrSet(map, key, computeValue) {
return map.has(key) ? map.get(key) : map.set(key, computeValue()).get(key);
}
//# sourceMappingURL=memoize.js.map