Skip to content

Instantly share code, notes, and snippets.

@tomasreichmann
Created August 24, 2018 11:11
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tomasreichmann/ce2455b68dbae6139632ea519ecea120 to your computer and use it in GitHub Desktop.
Save tomasreichmann/ce2455b68dbae6139632ea519ecea120 to your computer and use it in GitHub Desktop.
export const getTreeLeaves = (tree: any, getChildren = (node: any) => node && node.children) => {
const leaves = [];
const nodes = Array.isArray(tree) ? [...tree] : [tree];
let node;
let children;
while (
// tslint:disable-next-line:no-conditional-assignment ban-comma-operator
node = nodes.shift(), children = getChildren(node),
((children && children.length) || (leaves.push(node) && nodes.length))
) {
if (children) {
nodes.push(...children);
}
}
return leaves;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment