-
Notifications
You must be signed in to change notification settings - Fork 2
/
memoization.js
executable file
·45 lines (35 loc) · 955 Bytes
/
memoization.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
// Fibonacci with memoization
var fibonacci = (function ( ) {
var memo = [0, 1];
var fib = function (n) {
var result = memo[n];
if (typeof result !== 'number') {
result = fib(n-1) + fib(n-2);
memo[n] = result;
}
return result;
};
return fib;
}( ));
console.log(fibonacci(8));
// Generalize it with a memoizer function
var memoizer=function memoizer(memo, formula) {
var recur=function(n) {
var result=memo[n];
if (typeof result!=='number') {
result=formula(recur, n);
memo[n]=result;
}
return result;
};
return recur;
};
var fib2=memoizer([0,1], function(recur, n) {
return recur(n-1)+recur(n-2);
});
console.log(fib2(8));
// Now that we have a memoizer function we can also implement factorial
var factorial=memoizer([1,1], function(recur, n) {
return n*recur(n-1);
});
console.log(factorial(4));