Skip to content

Commit 0547031

Browse files
authored
Create 2623-memoize.js
1 parent c071774 commit 0547031

File tree

1 file changed

+24
-0
lines changed

1 file changed

+24
-0
lines changed

javascript/2623-memoize.js

+24
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
/**
2+
* @param {Function} fn
3+
* @return {Function}
4+
*/
5+
function memoize(fn) {
6+
let memo = {};
7+
return function (...args) {
8+
let argsjson = JSON.stringify(args);
9+
if (memo.hasOwnProperty(argsjson))
10+
return memo[argsjson];
11+
return memo[argsjson] = fn(...args);
12+
}
13+
}
14+
15+
/**
16+
* let callCount = 0;
17+
* const memoizedFn = memoize(function (a, b) {
18+
* callCount += 1;
19+
* return a + b;
20+
* })
21+
* memoizedFn(2, 3) // 5
22+
* memoizedFn(2, 3) // 5
23+
* console.log(callCount) // 1
24+
*/

0 commit comments

Comments
 (0)