Skip to content

Instantly share code, notes, and snippets.

@thakurarun
Last active April 19, 2021 04:54
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 thakurarun/706c4f1de0845bb22175a27878789739 to your computer and use it in GitHub Desktop.
Save thakurarun/706c4f1de0845bb22175a27878789739 to your computer and use it in GitHub Desktop.
Tree utils for searching, tracking and backtracking
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