Skip to content

Commit 18fd9a1

Browse files
committed
Memoization
1 parent a06d8b4 commit 18fd9a1

File tree

1 file changed

+31
-0
lines changed

1 file changed

+31
-0
lines changed

Memoization.js

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
function memoize(fn) {
2+
const cache = {};
3+
return (...args) => {
4+
const arg = JSON.stringify(args);
5+
6+
if (arg in cache) {
7+
console.log("fetching from cache");
8+
return cache[arg];
9+
} else {
10+
console.log("fetching for the first time");
11+
const result = fn.apply(this, args);
12+
cache[arg] = result;
13+
return result;
14+
}
15+
};
16+
}
17+
18+
const addThreeNums = (a, b, c) => a + b + c;
19+
20+
const add = memoize(addThreeNums);
21+
console.time();
22+
console.log(add(1, 2, 3));
23+
console.timeEnd();
24+
25+
console.time();
26+
console.log(add(1, 2, 3));
27+
console.timeEnd();
28+
29+
console.time();
30+
console.log(add(1, 2, 3));
31+
console.timeEnd();

0 commit comments

Comments
 (0)