Created
November 22, 2016 01:32
-
-
Save ethanresnick/fc43f6bc8848df8d66eaf0a87495b48f to your computer and use it in GitHub Desktop.
Tail recursive inner functions to remove accumulator vars from the api
This file contains 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
// 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