Created
June 15, 2011 19:20
-
-
Save mads-hartmann/1027862 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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