mirror of
https://github.com/devenperez/leetcode.git
synced 2026-06-13 03:27:07 +00:00
Time: 265 ms (94.13%), Space: 89.2 MB (46.21%) - LeetHub
This commit is contained in:
@@ -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
|
||||
*/
|
||||
Reference in New Issue
Block a user