Skip to content

Instantly share code, notes, and snippets.

@mads-hartmann
Created June 15, 2011 19:20
Show Gist options
  • Save mads-hartmann/1027862 to your computer and use it in GitHub Desktop.
Save mads-hartmann/1027862 to your computer and use it in GitHub Desktop.
// Attempt to do tail-recursion in JavaScript without getting a stack-overflow exception.
// This is horribly slow because of all of the extra stack frames pr. thunk.
// What would you call this? Lazy-tail-recursion?
var tailrec = function(f) {
for(var x = f() ; typeof x == "function" ; x = x()){}
return x;
};
var counter = function(){
var counter_tail = function(cnt){
if (cnt === 100000) {
return cnt;
} else {
return function(){ return counter_tail(cnt+1); };
}
};
return tailrec(function(){ return counter_tail(0); });
};
console.log(counter());
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment