Add src/index.js
This commit is contained in:
parent
a6496e6c98
commit
777211c671
1 changed files with 30 additions and 0 deletions
30
src/index.js
Normal file
30
src/index.js
Normal 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) );
|
Loading…
Reference in a new issue