Created
March 19, 2018 15:22
-
-
Save jameslaneconkling/997b8f71550eba53195fd7f07339f9f2 to your computer and use it in GitHub Desktop.
Tail Recursive Tree Recursion
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
const reduceChildren = ([first, ...rest], accumulator, project, reducer) => ( | |
rest.length === 0 ? | |
recurseTree(first, accumulator, project, reducer) : | |
reduceChildren( | |
rest, | |
recurseTree(first, accumulator, project, reducer), | |
project, | |
reducer | |
) | |
); | |
const recurseTree = (tree, accumulator, project, reducer) => ( | |
tree.length === 1 ? | |
reducer(accumulator, project(tree)) : | |
reduceChildren( | |
tree.slice(1), | |
reducer(accumulator, project(tree)), | |
project, | |
reducer | |
) | |
); | |
var tree = ['root', | |
['child1', [1], [2], [3]], | |
['child2', [10], [11], ['grandchild2', [22], [23]]], | |
['child3', [30]], | |
[100]]; | |
// flatten tree | |
const identity = (x) => x; | |
const append = (list, item) => [...list, item]; | |
recurseTree(tree, [], identity, append); | |
// collect all leaf nodes | |
const leafValue = ([value, ...rest]) => rest.length === 0 ? [value] : []; | |
const concat = (list, items) => [...list, ...items]; | |
recurseTree(tree, [], leafValue, concat); | |
// sum all leaf nodes | |
const leafValue2 = ([value, ...rest]) => rest.length === 0 ? value : 0; | |
const sum = (acc, item) => acc + item; | |
recurseTree(tree, 0, leafValue2, sum); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment