-
Notifications
You must be signed in to change notification settings - Fork 0
/
memoize.js
40 lines (34 loc) · 1.12 KB
/
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
const memoize = (callback) => {
let cache = {}
return (...args) => {
if (n in cache) {
return cache[n]
} else {
let result = callback(...args)
cache[n] = result
return result
}
}
}
// When we run the body of this function all the variables
// in the scope are gonna be re-initialize, but the "cache" variables will stay the same
// Basically the cache / callback stays the stay
// The only thing that changes is the arguements
function memoize(fn) {
/* we'll use this object to store the results */
let cache = {};
/**
* Returns a function that will receive the arguments
* that will be passed to the memoized function (fn).
*/
return (...args) => {
/* We stringify the arguments in case they're non-primitive values */
const cacheKey = JSON.stringify(args);
/* were the arguments already passed? if no, then store the result */
if (!(cacheKey in cache)) {
cache[cacheKey] = fn(...args);
}
/* We then return the stored result */
return cache[cacheKey];
};
}