-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathcaching.js
More file actions
36 lines (29 loc) · 936 Bytes
/
caching.js
File metadata and controls
36 lines (29 loc) · 936 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
// caching is a way to store the result of a function so that we dont have to calculate it again.
function cache(fn, context = this) {
const cache = {};
return function (...args) {
if (cache[args]) {
return cache[args];
}
const result = fn.apply(context, args);
cache[args] = result;
return result;
}
}
const square = (num1, num2) => {
for (let i = 1; i <= 100000000; i++) { }
return num1 * num2;
}
console.time('function call 1');
console.log(square(2, 3));
console.timeEnd('function call 1');
console.time('function call 2');
console.log(square(2, 3));
console.timeEnd('function call 2')
const cachedSquare = cache(square);
console.time('cached function call 1');
console.log(cachedSquare(2, 3));
console.timeEnd('cached function call 1');
console.time('cached function call 2');
console.log(cachedSquare(2, 3));
console.timeEnd('cached function call 2')