Last active
August 24, 2018 11:11
-
-
Save tomasreichmann/249d6e659f879126501ff739dead01c9 to your computer and use it in GitHub Desktop.
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
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