From dd5aeef5f6ea5fb884dbf8ae8cf4a654c917f1ba Mon Sep 17 00:00:00 2001 From: Matej Focko Date: Sun, 14 May 2023 00:05:44 +0200 Subject: [PATCH] =?UTF-8?q?problems(js):=20add=20=E2=80=9C2623.=20Memoize?= =?UTF-8?q?=E2=80=9D?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: Matej Focko --- problems/memoize.js | 28 ++++++++++++++++++++++++++++ 1 file changed, 28 insertions(+) create mode 100644 problems/memoize.js diff --git a/problems/memoize.js b/problems/memoize.js new file mode 100644 index 0000000..8b26a4b --- /dev/null +++ b/problems/memoize.js @@ -0,0 +1,28 @@ +/** + * @param {Function} fn + */ +function memoize(fn) { + let cache = new Map(); + + return function(...args) { + let key = JSON.stringify(args); + + if (!cache.has(key)) { + cache.set(key, fn(...args)); + } + + return cache.get(key); + } +} + + +/** + * let callCount = 0; + * const memoizedFn = memoize(function (a, b) { + * callCount += 1; + * return a + b; + * }) + * memoizedFn(2, 3) // 5 + * memoizedFn(2, 3) // 5 + * console.log(callCount) // 1 + */