forked from codesONLY/JavaScriptONLY
-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathmemoizeOne.js
More file actions
38 lines (34 loc) · 698 Bytes
/
memoizeOne.js
File metadata and controls
38 lines (34 loc) · 698 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
31
32
33
34
35
36
37
38
/**
* Do not change the function name
**/
function memoizeOne(fn, isEqual) {
let cache = {};
function hasher(args) {
return args.join(",");
}
return function (...args) {
const hash = hasher(args);
if (cache[hash]) {
return cache[hash];
}
cache = {};
const res = fn.apply(null, args);
cache[hash] = res;
return res;
};
}
function add(a, b) {
console.print("called");
return a + b;
}
function isEqual(a, b) {
if (a === b) {
return true;
}
return false;
}
const memoizeAdd = memoizeOne(add, isEqual);
console.print(memoizeAdd(2, 3));
console.print(memoizeAdd(2, 3));
console.print(memoizeAdd(3, 4));
console.print(memoizeAdd(5, 6));