Last active
October 20, 2015 20:05
-
-
Save gemmadlou/0d40d847c72f3b653390 to your computer and use it in GitHub Desktop.
Maximum Call Stack Size Solution
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
// Must thank Mark McDonnell of Integralist | |
// http://www.integralist.co.uk/posts/js-recursion.html | |
// Below is his solution to prevent maximum call stack errors caused by calling | |
// functions recursively beyond the stack limit. | |
function tco(f) { | |
var value; | |
var active = false; | |
var accumulated = []; | |
return function accumulator() { | |
accumulated.push(arguments); | |
if (!active) { | |
active = true; | |
while (accumulated.length) { | |
value = f.apply(this, accumulated.shift()); | |
} | |
active = false; | |
return value; | |
} | |
} | |
} | |
var sum = tco(function(x, y) { | |
if (y > 0) { | |
return sum(x + 1, y - 1) | |
} | |
else { | |
return x | |
} | |
}); | |
sum(1, 100000); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment