-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmemoization.js
More file actions
32 lines (27 loc) · 907 Bytes
/
Copy pathmemoization.js
File metadata and controls
32 lines (27 loc) · 907 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
/**
* Memoization is a form of caching where the return value of a
* function is cached based on its parameters. If the parameter
* of that function is not changed, the cached version of the
* function is returned.
*
* Although using memoization saves time, it results in larger
* consumption of memory since we are storing all the computed results.
*/
function memoizedAddTo256(){
var cache = {};
return function(num){
if(num in cache){
console.log("cached value");
return cache[num]
}
else{
cache[num] = num + 256;
return cache[num];
}
}
}
var memoizedFunc = memoizedAddTo256();
console.log(memoizedFunc(20)); // Normal return
// if we run memoizedFunc function with the same parameter,
// instead of computing the result again, it returns the cached result.
console.log(memoizedFunc(20)); // Cached return