-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathMemoize.js
42 lines (31 loc) · 825 Bytes
/
Memoize.js
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
31
32
33
34
35
36
37
38
39
40
41
42
// Given a function fn, return a memoized version of that function.
// A memoized function is a function that will never be called twice
// with the same inputs. Instead it will return a cached value.
/**
* @param {Function} fn
*/
function memoize(fn) {
const cache = {};
return function(...args) {
const key = JSON.stringify(args);
if (key in cache) {
return cache[key];
}
const result = fn.apply(this, args);
cache[key] = result;
return result;
}
}
const memoizedSum = memoize(function(a, b) {
return a + b;
});
/**
* 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
*/