add findInTree function in utils

This commit is contained in:
Géry Debongnie
2019-02-01 12:47:01 +01:00
parent c46bad6e35
commit 37a8b3c7e7
2 changed files with 35 additions and 1 deletions
+20
View File
@@ -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;
}
+15 -1
View File
@@ -3,7 +3,8 @@ import {
htmlTrim,
idGenerator,
memoize,
debounce
debounce,
findInTree
} from "../../src/ts/core/utils";
describe("escape", () => {
@@ -77,3 +78,16 @@ describe("debounce", () => {
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);
});
});