Skip to content

Commit e6f6aa8

Browse files
Speed up your recursive functions with a memoizer.
1 parent 23120b6 commit e6f6aa8

File tree

1 file changed

+26
-0
lines changed

1 file changed

+26
-0
lines changed

memoizer.js

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
function memoizer(memo, formula) {
2+
var recur = function (n) {
3+
var result = memo[n];
4+
5+
if (typeof result !== 'number') {
6+
result = formula(recur, n);
7+
memo[n] = result;
8+
}
9+
10+
return result;
11+
};
12+
13+
return recur;
14+
};
15+
16+
// The memo variable we pass is an array whose indexes are the inputs to the recursive function
17+
// and whose values are the outputs from the recursive function.
18+
// e.g. the factorial of 0 is 1, and the factorial of 1 is 1, hence the memo array: [1, 1]
19+
var factorial = memoizer([1, 1], function (recur, n) {
20+
return n * recur(n - 1);
21+
});
22+
23+
// The fibonacci of 0 is 0, and fibonacci of 1 is 1, hence the memo array: [0, 1]
24+
var fibonacci = memoizer([0, 1], function (recur, n) {
25+
return recur(n - 1) + recur(n - 2);
26+
});

0 commit comments

Comments
 (0)