Skip to content

Instantly share code, notes, and snippets.

@munro
Created February 22, 2012 23:21
Show Gist options
  • Save munro/1888313 to your computer and use it in GitHub Desktop.
Save munro/1888313 to your computer and use it in GitHub Desktop.
Tail Call Optimization
// http://paulbutler.org/archives/tail-recursion-in-python/
function tailCall(fn) {
return function () {
fn = fn.apply(this, arguments);
while (typeof fn === 'function') {
fn = fn();
}
return fn;
};
}
var tailEven,
tailOdd;
tailEven = function (x) {
if (x === 0) {
return true;
} else {
return function () {
return tailOdd(x - 1);
};
}
};
tailOdd = function (x) {
if (x === 0) {
return false;
} else {
return function () {
return tailEven(x - 1);
};
}
};
var even = tailCall(tailEven);
var odd = tailCall(tailOdd);
console.log(even(100));
console.log(odd(100));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment