mirror of
https://github.com/captbaritone/webamp.git
synced 2026-07-22 01:29:22 +00:00
Add more tree search utilities
This commit is contained in:
parent
66dc33c368
commit
905268dac2
2 changed files with 40 additions and 1 deletions
|
|
@ -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;
|
||||
};
|
||||
}
|
||||
|
|
|
|||
|
|
@ -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;
|
||||
}
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue