diff --git a/src/index.js b/src/index.js new file mode 100644 index 0000000..ee9b637 --- /dev/null +++ b/src/index.js @@ -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) ); \ No newline at end of file