3 ms·
Map is really handy for writing memoization-type functions: const memoize = func => { const cache = new Map(); const memoized = arg => { const
by rimunroe 8y ago
Map is really handy for writing memoization-type functions:
const memoize = func => {
const cache = new Map();
const memoized = arg => {
const cached = cache.get(arg);
if (cached !== undefined) {
return cached;
}
const result = func(arg);
cache.set(arg, result);
return result;
};
memoized.clearCache = cache.clear.bind(cache);
return memoized;
};
(Also, you could use WeakMap instead of Map if you knew the memoized function would only ever receive objects as arguments.)