mirror of
https://github.com/odoo/owl.git
synced 2025-10-06 19:59:41 +07:00
add findInTree function in utils
This commit is contained in:
@@ -83,3 +83,23 @@ export function debounce(
|
|||||||
}
|
}
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
|
interface Tree<T> {
|
||||||
|
children: T[];
|
||||||
|
}
|
||||||
|
|
||||||
|
export function findInTree<T extends Tree<T>>(
|
||||||
|
tree: T,
|
||||||
|
predicate: (t: T) => boolean
|
||||||
|
): T | null {
|
||||||
|
if (predicate(tree)) {
|
||||||
|
return tree;
|
||||||
|
}
|
||||||
|
for (let child of tree.children) {
|
||||||
|
let match = findInTree(child, predicate);
|
||||||
|
if (match) {
|
||||||
|
return match;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|||||||
@@ -3,7 +3,8 @@ import {
|
|||||||
htmlTrim,
|
htmlTrim,
|
||||||
idGenerator,
|
idGenerator,
|
||||||
memoize,
|
memoize,
|
||||||
debounce
|
debounce,
|
||||||
|
findInTree
|
||||||
} from "../../src/ts/core/utils";
|
} from "../../src/ts/core/utils";
|
||||||
|
|
||||||
describe("escape", () => {
|
describe("escape", () => {
|
||||||
@@ -77,3 +78,16 @@ describe("debounce", () => {
|
|||||||
expect(n).toBe(1);
|
expect(n).toBe(1);
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
|
describe("findInTree", () => {
|
||||||
|
test("can find stuff in tree", () => {
|
||||||
|
let tree = {
|
||||||
|
id: 1,
|
||||||
|
children: [{ id: 2, children: [] }, { id: 3, key: "hello", children: [] }]
|
||||||
|
};
|
||||||
|
const match1 = findInTree(tree, t => t.id === 3);
|
||||||
|
expect((<any>match1).key).toBe("hello");
|
||||||
|
const match2 = findInTree(tree, t => t.id === 4);
|
||||||
|
expect(match2).toBe(null);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|||||||
Reference in New Issue
Block a user