Skip to content

Instantly share code, notes, and snippets.

@ethanresnick
Created November 22, 2016 01:32
Show Gist options
  • Save ethanresnick/fc43f6bc8848df8d66eaf0a87495b48f to your computer and use it in GitHub Desktop.
Save ethanresnick/fc43f6bc8848df8d66eaf0a87495b48f to your computer and use it in GitHub Desktop.
Tail recursive inner functions to remove accumulator vars from the api
// Non tail recursive; will have a stack overflow.
function sum(list) {
if(list.length === 0) {
return 0;
}
return list[0] + sum(list.slice(1));
}
// Naive tail recursive (ugly api)
function sum2(list, total = 0) {
if(list.length === 0) {
return total;
}
return sum2(list.slice(1), total + list[0]);
}
// Tail recursive using an inner function for a clean api
function sum3(list) {
let sumAccumulator = (list, total) => {
return list.length === 0 ?
total :
sumAccumulator(list.slice(1), total + list[0]);
};
return sumAccumulator(list, 0);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment