function slow(x) {
// there can be a heavy CPU-intensive job here
alert(`Called with ${x}`);
return x;
}
function cachingDecorator(func) {
let cache = new Map();
return function(x) {
if (cache.has(x)) { // if the result is in the map
return cache.get(x); // return it
}
let result = func(x); // otherwise call func
cache.set(x, result); // and cache (remember) the result
console.log(cache);
return result;
};
}
slow = cachingDecorator(slow);
console.log( slow(1) ); // slow(1) is cached
console.log( "Again: " + slow(1) ); // the same
console.log( slow(2) ); // slow(2) is cached
console.log( "Again: " + slow(2) ); // the same as the previous line
Created
December 14, 2018 03:16
-
-
Save andrit/622ca9d28c269c37c262435d0c246a1d to your computer and use it in GitHub Desktop.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment