Created
January 18, 2011 14:19
-
-
Save xulapp/784481 to your computer and use it in GitHub Desktop.
tail recursive
This file contains hidden or 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
| 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