From e2c8959107150f8bf7073c8ad767663e87dcc356 Mon Sep 17 00:00:00 2001 From: terminaldweller Date: Fri, 5 Jan 2024 16:56:35 -0500 Subject: 2623 --- 2623/main.js | 30 ++++++++++++++++++++++++++++++ 1 file changed, 30 insertions(+) create mode 100644 2623/main.js (limited to '2623') diff --git a/2623/main.js b/2623/main.js new file mode 100644 index 0000000..966025f --- /dev/null +++ b/2623/main.js @@ -0,0 +1,30 @@ +#!/usr/bin/env node +"use strict"; + +/** + * @param {Function} fn + * @return {Function} + */ +function memoize(fn) { + const cache = {}; + return function memoized(...args) { + const key = JSON.stringify(args); + if (key in cache) { + return cache[key]; + } + const result = fn(...args); + cache[key] = result; + return result; + }; +} + +/** + * 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 + */ -- cgit v1.2.3