-
Notifications
You must be signed in to change notification settings - Fork 0
/
memoize.js
40 lines (30 loc) · 855 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
const memoize3 = fn => {
let cache = {};
const PRIMITIVES = ["number", "string", "boolean"];
return (...args) => {
let strX =
args.length === 1 && PRIMITIVES.includes(typeof args[0]) ?
args[0] :
JSON.stringify(args);
return strX in cache ? cache[strX] : (cache[strX] = fn(...args));
};
};
const memoize = fn => {
let cache = {};
return x => (x in cache ? cache[x] : (cache[x] = fn(x)));
};
const memoize2 = fn => {
if (fn.length === 1) {
let cache = {};
return x => (x in cache ? cache[x] : (cache[x] = fn(x)));
} else {
return fn;
}
};
const memoize4 = fn => {
let cache = {};
return (...args) => {
let strX = JSON.stringify(args);
return strX in cache ? cache[strX] : (cache[strX] = fn(...args));
};
};