Add src/index.js

This commit is contained in:
Adam Cooper 2024-11-25 00:53:23 +00:00
parent a6496e6c98
commit 777211c671

30
src/index.js Normal file
View file

@ -0,0 +1,30 @@
function slow(x) {
// there can be a heavy CPU-intensive job here
console.info(`Called with ${x}`);
return x;
}
function cachingDecorator(func) {
let cache = new Map();
return function(x) {
if (cache.has(x)) { // if there's such key in cache
console.info("Cache hit!");
return cache.get(x); // read the result from it
}
let result = func(x); // otherwise call func
console.info("Cache miss!");
cache.set(x, result); // and cache (remember) the result
return result;
};
}
slow = cachingDecorator(slow);
console.info( slow(1) ); // slow(1) is cached and the result returned
console.info( "Again: " + slow(1) ); // slow(1) result returned from cache
console.info( slow(2) ); // slow(2) is cached and the result returned
console.info( "Again: " + slow(2) );