-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathmomization.js
More file actions
50 lines (46 loc) · 1.23 KB
/
momization.js
File metadata and controls
50 lines (46 loc) · 1.23 KB
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
// NOTE Memoization choose speed calculations over memory consumbtion
// This function caches the result
const memoizeFactorial = () => {
const previouslyFetched = {};
return function calc(num) {
if (previouslyFetched[num]) {
// console.log("cached before");
return previouslyFetched[num];
}
// For loop used in performance measure purpose
for (let i = 0; i < 10e5; i++) {}
const result = num ? num * calc(num - 1) : 1;
previouslyFetched[num] = result;
return result;
};
};
const memFact = memoizeFactorial();
const normalFact = num => {
// For loop used in performance measure purpose
for (let i = 0; i < 10e5; i++) {}
return num ? num * normalFact(num - 1) : 1;
};
const startMemo = Date.now();
console.log("First result : ", memFact(85));
console.log(Date.now() - startMemo);
memFact(86);
memFact(87);
memFact(88);
memFact(88);
memFact(88);
memFact(88);
memFact(88);
memFact(50);
console.log(Date.now() - startMemo);
const start = Date.now();
console.log("Normal function");
console.log("First result : ", normalFact(85));
console.log(Date.now() - start);
normalFact(86);
normalFact(87);
normalFact(88);
normalFact(88);
normalFact(88);
normalFact(88);
normalFact(88);
console.log(Date.now() - start);