Time: 265 ms (94.13%), Space: 89.2 MB (46.21%) - LeetHub

This commit is contained in:
Deven
2024-11-25 12:44:44 -05:00
parent 1759076719
commit 398fc1e3d7
+28
View File
@@ -0,0 +1,28 @@
/**
* @param {Function} fn
* @return {Function}
*/
function memoize(fn) {
memo = {}
return function(...args) {
let key = JSON.stringify(args)
let val = memo[key]
if (val !== undefined) return val
val = fn(...args)
memo[key] = val
return val
}
}
/**
* 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
*/