Skip to content

Instantly share code, notes, and snippets.

@tdegrunt
Forked from Gozala/example.js
Created January 29, 2012 20:41
Show Gist options
  • Save tdegrunt/1700543 to your computer and use it in GitHub Desktop.
Save tdegrunt/1700543 to your computer and use it in GitHub Desktop.
Workaround for lack of "tail call optimization" in JS
// Lack of tail call optimization in JS
var sum = function(x, y) {
return y > 0 ? sum(x + 1, y - 1) :
y < 0 ? sum(x - 1, y + 1) :
x
}
sum(20, 100000) // => RangeError: Maximum call stack size exceeded
// Using workaround
var sum = tco(function(x, y) {
return y > 0 ? sum(x + 1, y - 1) :
y < 0 ? sum(x - 1, y + 1) :
x
})
sum(20, 100000) // => 100020
function tco(f) {
/**
Takes `f` function and returns one that may be used for tail recursive algorithms.
**/
var active = false, value, accumulated, args
return function accumulator() {
accumulated = arguments
if (!active) {
active = true
while (accumulated) {
args = accumulated
accumulated = null
value = f.apply(this, args)
}
active = false
return value
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment