Skip to content

Instantly share code, notes, and snippets.

@kiinlam
Created November 22, 2017 07:08
Show Gist options
  • Save kiinlam/de7496a24e5e9cea0956233be6e9108a to your computer and use it in GitHub Desktop.
Save kiinlam/de7496a24e5e9cea0956233be6e9108a to your computer and use it in GitHub Desktop.
尾递归优化tco
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)
// 100001
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment