Last active
April 19, 2021 04:54
-
-
Save thakurarun/706c4f1de0845bb22175a27878789739 to your computer and use it in GitHub Desktop.
Tree utils for searching, tracking and backtracking
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
export function treeForwardTracking( | |
treeNodes: TreeNode[], | |
action: (TreeNode: TreeNode) => void | |
): void { | |
treeNodes.forEach((node) => { | |
action(node); | |
if (node.children) { | |
treeForwardTracking(node.children, action); | |
} | |
}); | |
} | |
export function treeBackwardTracking( | |
treeNodes: TreeNode[], | |
action: (TreeNode: TreeNode) => void | |
): void { | |
treeNodes.forEach((node) => { | |
if (node.children) { | |
treeBackwardTracking(node.children, action); | |
} | |
action(node); | |
}); | |
} | |
export function findTreeNodesByIds( | |
tree: TreeNode[], | |
ids: (string | undefined | null)[] | |
): TreeNode[] { | |
ids = ids.filter((id) => id); | |
if (ids.length === 0) { | |
return []; | |
} | |
return tree.reduce((matchingNodes: TreeNode[], node: TreeNode) => { | |
if (ids.includes(node.id)) { | |
matchingNodes.push(node); | |
} | |
if (node.children) { | |
matchingNodes.push(...findTreeNodesByIds(node.children, ids)); | |
} | |
return matchingNodes; | |
}, []); | |
} | |
export interface TreeNode { | |
name: string; | |
key: string; | |
id: string; | |
parentId: string | undefined; | |
focused?: boolean; | |
selected?: boolean; | |
disabled?: boolean; | |
expanded?: boolean; | |
partiallySelected?: boolean; | |
children?: Array<TreeNode>; | |
itemCount?: number; | |
additionalText?: string; | |
badgeDisabled?: boolean; | |
showParentSelection?: boolean; | |
hidden?: boolean; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment