Reducing Javascript Recursion, and Other Fun Tricks
Posted on 01/30/2009 @ 04:50AMHere's some brain candy for all you algorith-maniacs (that's right, I said it) out there. Check out Speed up your JavaScript, Part 2.
My favorite is Doug Crockford's memoization function, which can dramatically reduce recursive calls in cases such as this:
/*
* Normal recursion; whole lotta recursive calls
*/
function fibonacci (n) {
return n < 2 ? n :
fibonacci(n - 1) +
fibonacci(n - 2);
};
/*
* Cached recursion; called once for each value of n
*/
function memoizer(memo, fundamental) {
var shell = function (n) {
var result = memo[n];
if (typeof result !== 'number') {
result = fundamental(shell, n);
memo[n] = result;
}
return result;
};
return shell;
};
He then applies this to the Fibonacci sequence generator:
var fibonacci =
memoizer([0, 1], function (recur, n) {
return recur(n - 1) + recur(n - 2);
});