Skip to content

Instantly share code, notes, and snippets.

@xulapp
Created January 18, 2011 14:19
Show Gist options
  • Select an option

  • Save xulapp/784481 to your computer and use it in GitHub Desktop.

Select an option

Save xulapp/784481 to your computer and use it in GitHub Desktop.
tail recursive
function tailRecursive(func) {
var firstcall = true;
var targs;
var CONTINUE = {};
return function() {
var args = arguments;
var err, threw;
if (firstcall) {
firstcall = false;
try {
while (true) {
var result = func.apply(this, args);
if (result === CONTINUE) {
args = targs;
} else {
return result;
}
}
} catch(e) {
threw = true;
err = e;
} finally {
firstcall = true;
if (threw)
throw err;
}
} else {
targs = args;
return CONTINUE;
}
};
}
var sum = tailRecursive(function(n, acc) {
acc = acc || 0;
if (n === 0)
return acc;
return sum(n - 1, acc + n);
});
sum(100000);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment