JSFiddle - React, Tailwind, and code Playground
by ccnokes
JavaScript
function memoize(fn, resolver) {
const cache = new Map();
const memoized = function(...args) {
// if we have a resolver defined, use that, otherwise, default to the first arg
const key = resolver ? resolver.apply(null, args) : args[0];
if (cache.has(key)) {
//console.log('cache hit for', key);
return cache.get(key);
} else {
//console.log('cache miss for', key);
const result = fn.apply(null, args);
cache.set(key, result);
return result;
}
};
memoized.getCache = () => cache;
return memoized;
}
/* just for easy tests here */
function assert(result, message) {
if (!result) {
throw new Error(message);
} else {
console.log('test passed!');
}
}
/* === tests === */
function factorialize(n) {
if (n < 0) {
return -1;
} else if (n === 0) {
return 1;
} else {
return (n * factorialize(n - 1));
}
}
const memoizedFactorialize = memoize(factorialize);
memoizedFactorialize(5);
memoizedFactorialize(5);
memoizedFactorialize(5);
assert(
memoizedFactorialize.getCache().size === 1,
`memoizedFactorialize cache size should = 1`
);
memoizedFactorialize(6);
assert(
memoizedFactorialize.getCache().size === 2,
`memoizedFactorialize cache size should = 2`
);
const getElementBackgroundCSS = memoize(el => getComputedStyle(el).background);
getElementBackgroundCSS(document.body);
getElementBackgroundCSS(document.body);
assert(
getElementBackgroundCSS.getCache().size === 1,
`getElementBackgroundCSS cache size should = 1`
);