From 777211c671086f80656ec32275f100433dedd222 Mon Sep 17 00:00:00 2001 From: adam Date: Mon, 25 Nov 2024 00:53:23 +0000 Subject: [PATCH] Add src/index.js --- src/index.js | 30 ++++++++++++++++++++++++++++++ 1 file changed, 30 insertions(+) create mode 100644 src/index.js 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