Skip to content

Instantly share code, notes, and snippets.

@tomasreichmann
Last active 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/249d6e659f879126501ff739dead01c9 to your computer and use it in GitHub Desktop.
Save tomasreichmann/249d6e659f879126501ff739dead01c9 to your computer and use it in GitHub Desktop.
export const indexOfTreeNode = (
node: any,
tree: any,
matchNode = (nodeA: any, nodeB: any) => (nodeA === nodeB),
getChildren = (node: any) => node && node.children || [],
indexes: number[] = []
): number[] => {
const nodes = Array.isArray(tree) ? [...tree] : [tree];
for (let nodeIndex = 0; nodeIndex < nodes.length; nodeIndex++) {
const currentNode = nodes[nodeIndex];
// match current node
if (matchNode(currentNode, node)) {
return [...indexes, nodeIndex];
}
// check children
const childrenMatchIndexes = indexOfTreeNode(
node,
getChildren(currentNode),
matchNode,
getChildren,
[...indexes, nodeIndex]
);
if (childrenMatchIndexes !== null) {
return childrenMatchIndexes;
}
}
return null;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment