Add more tree search utilities

This commit is contained in:
Jordan Eldredge 2019-08-29 08:46:55 -07:00
parent 66dc33c368
commit 905268dac2
2 changed files with 40 additions and 1 deletions

View file

@ -16,3 +16,22 @@ export function getTop(uid) {
return Number(node.attributes.y) || 0;
};
}
export function getPathToUid(uid: number) {
return state => {
return Utils.findPathToNode(state.xmlTree, node => node.uid === uid);
};
}
export function getNodeAtPath(path: number[]) {
return state => {
let node = state.xmlTree;
path.forEach(offset => {
if (node == null) {
return null;
}
node = node.children[offset];
});
return node;
};
}

View file

@ -138,8 +138,28 @@ export function unimplementedWarning(name: string): void {
console.warn(`Executing unimplemented MAKI function: ${name}`);
}
// Bredth-first search in a tree that returns the path to the node
export function findPathToNode<T extends { children: T[] }>(
node: T,
predicate: (candidate: T) => boolean
): number[] {
if (predicate(node)) {
return [];
}
const children = node.children || [];
for (let i = 0; i < children.length; i++) {
const child = children[i];
const found = findPathToNode(child, predicate);
if (found != null) {
return [i, ...found];
}
}
return null;
}
// Bredth-first search in a tree
export function findInTree(node, predicate) {
export function findInTree<T extends { children: T[] }>(node: T, predicate): T {
if (predicate(node)) {
return node;
}