Skip to content

Instantly share code, notes, and snippets.

@fitzgen
Created December 21, 2010 12:59
Show Gist options
  • Save fitzgen/749901 to your computer and use it in GitHub Desktop.
Save fitzgen/749901 to your computer and use it in GitHub Desktop.
My TCO -- doesn't work with mutual recursion
function toArray(obj, i) {
return Array.prototype.slice.call(obj, i || 0);
}
function tco(fn) {
return function () {
var args = toArray(arguments),
shouldContinue = true,
recur = function () {
shouldContinue = true;
return toArray(arguments);
};
while ( shouldContinue ) {
shouldContinue = false;
args = fn.apply(this, [recur].concat(args));
}
return args;
};
}
var factorial = tco(function (factorial, n, acc) {
acc = acc || 1;
return n < 2
? acc
: factorial(n - 1, acc * n);
});
factorial(170);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment