Skip to content

Instantly share code, notes, and snippets.

@jameslaneconkling
Created March 19, 2018 15:22
Show Gist options
  • Save jameslaneconkling/997b8f71550eba53195fd7f07339f9f2 to your computer and use it in GitHub Desktop.
Save jameslaneconkling/997b8f71550eba53195fd7f07339f9f2 to your computer and use it in GitHub Desktop.
Tail Recursive Tree Recursion
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