-
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathmemoize.js
74 lines (56 loc) · 1.81 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
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
/**
* Memoizes a function
* @param {string} name The name of the element
* @param {array} params The element params
* @returns {any}
*/
// const memoize = (name) => {
// };
const memoize = function (func) {
const memoizedElements = {};
const slice = Array.prototype.slice;
return function () {
// const stringifiedParams = params.toString();
// const stringifiedParams = JSON.stringify(arguments);
const stringifiedParams = slice.call(arguments);
// console.log("stringified params", stringifiedParams, memoizedElements);
if (!(stringifiedParams in memoizedElements)) {
memoizedElements[stringifiedParams] = func.apply(
this,
slice.call(arguments)
);
}
return memoizedElements[stringifiedParams];
};
};
function sum(a, b) {
const result = a + b;
console.log("computing", result);
return result;
}
const memoizedSum = memoize(sum);
console.log(memoizedSum(1, 3));
console.log(memoizedSum(1, 3));
console.log(memoizedSum(1, 3));
function sumWithObjects({ a, b }) {
const result = a + b;
console.log("computing with objects", result);
return result;
}
const memoizedSumWithObjects = memoize(sumWithObjects);
console.log(memoizedSumWithObjects({ a: 1, b: 3 }));
console.log(memoizedSumWithObjects({ a: 1, b: 4 }));
console.log(memoizedSumWithObjects({ a: 1, b: 3 }));
function recursiveFactorial(n) {
if (n < 1) return 1;
console.log("computing recursive factorial of", n);
return n * recursiveFactorial(n - 1);
}
// const memoizedRecursiveFactorial = memoize(recursiveFactorial);
const memoizedRecursiveFactorial = memoize(recursiveFactorial);
const number = 50;
// const number = 10;
// const number = 5;
console.log(memoizedRecursiveFactorial(number));
console.log(memoizedRecursiveFactorial(number));
console.log(memoizedRecursiveFactorial(number));