1
0
Fork 0
mirror of https://gitlab.com/mfocko/LeetCode.git synced 2024-09-19 17:56:55 +02:00

problems(js): add “2623. Memoize”

Signed-off-by: Matej Focko <mfocko@redhat.com>
This commit is contained in:
Matej Focko 2023-05-14 00:05:44 +02:00
parent f66cfc3cae
commit dd5aeef5f6
Signed by: mfocko
GPG key ID: 7C47D46246790496

28
problems/memoize.js Normal file
View file

@ -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
*/