-
Notifications
You must be signed in to change notification settings - Fork 22
Expand file tree
/
Copy pathmemoize.js
More file actions
30 lines (23 loc) · 681 Bytes
/
memoize.js
File metadata and controls
30 lines (23 loc) · 681 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
function memoize(fn) {
const cache = new Map();
return function(...args) {
const key = JSON.stringify(args);
if(cache.has(key)){
console.log('memoized return ')
return cache.get(key)
}
const result = fn(...args);
cache.set(key, result);
return result;
}
}
// Example usage:
function add(a, b) {
console.log("Calculating sum...");
return a + b;
}
const memoizeAddFn = memoize(add);
console.log(memoizeAddFn(1, 2)); // Calculates and returns 3
console.log(memoizeAddFn(1, 2)); // Returns cached 3 without calculating
console.log(memoizeAddFn(2, 3)); // Calculates and returns 5
console.log(memoizeAddFn(2, 3)); // Returns cached 5