Memoize (or cache) a Function in JavaScript. Create an empty cache by instantiating a new Map object. Return a function which takes a single argument to be supplied to the memoized function by first checking if the function's output for that specific input value is already cached, or store and return it if not. The function keyword must be used in order to allow the memoized function to have its this context changed if necessary. Allow access to the cache by setting it as a property on the returned function.
// https://www.30secondsofcode.org/snippet/memoize
// https://github.com/30-seconds/30-seconds-of-code
const memoize = fn => {
const cache = new Map();
const cached = function(val) {
return cache.has(val)
? cache.get(val)
: cache.set(val, fn.call(this, val)) && cache.get(val);
};
cached.cache = cache;
return cached;
};
//
// Compiled
var memoize = function memoize(fn) {
var cache = new Map();
var cached = function cached(val) {
return cache.has(val)
? cache.get(val)
: cache.set(val, fn.call(this, val)) && cache.get(val);
};
cached.cache = cache;
return cached;
};
// --------------------------------------------------
// Example Usage
// --------------------------------------------------
// See the `anagrams` snippet (https://github.com/30-seconds/30-seconds-of-code):
const anagramsCached = memoize(anagrams);
anagramsCached("javascript"); // takes a long time
anagramsCached("javascript"); // returns virtually instantly since it's now cached
console.log(anagramsCached.cache); // The cached anagrams map