feat: add tree.siblings
This commit is contained in:
parent
5bf1c93ead
commit
013f9a2bbc
|
@ -21,6 +21,14 @@ export class Tree<T> {
|
||||||
return n && n.children.length > 0 ? n.children[0].value : null;
|
return n && n.children.length > 0 ? n.children[0].value : null;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
siblings(t: T): T[] {
|
||||||
|
const p = findPath(t, this._root, []);
|
||||||
|
if (p.length < 2) return [];
|
||||||
|
|
||||||
|
const c = p[p.length - 2].children.map(c => c.value);
|
||||||
|
return c.filter(cc => cc !== t);
|
||||||
|
}
|
||||||
|
|
||||||
pathFromRoot(t: T): T[] { return findPath(t, this._root, []).map(s => s.value); }
|
pathFromRoot(t: T): T[] { return findPath(t, this._root, []).map(s => s.value); }
|
||||||
|
|
||||||
contains(tree: Tree<T>): boolean { return contains(this._root, tree._root); }
|
contains(tree: Tree<T>): boolean { return contains(this._root, tree._root); }
|
||||||
|
|
|
@ -24,6 +24,12 @@ describe('tree', () => {
|
||||||
expect(t.firstChild(2)).toEqual(null);
|
expect(t.firstChild(2)).toEqual(null);
|
||||||
});
|
});
|
||||||
|
|
||||||
|
it("should return the siblings of a node", () => {
|
||||||
|
const t = new Tree<any>(new TreeNode<number>(1, [new TreeNode<number>(2, []), new TreeNode<number>(3, [])]));
|
||||||
|
expect(t.siblings(2)).toEqual([3]);
|
||||||
|
expect(t.siblings(1)).toEqual([]);
|
||||||
|
});
|
||||||
|
|
||||||
it("should return the path to the root", () => {
|
it("should return the path to the root", () => {
|
||||||
const t = new Tree<any>(new TreeNode<number>(1, [new TreeNode<number>(2, [])]));
|
const t = new Tree<any>(new TreeNode<number>(1, [new TreeNode<number>(2, [])]));
|
||||||
expect(t.pathFromRoot(2)).toEqual([1, 2]);
|
expect(t.pathFromRoot(2)).toEqual([1, 2]);
|
||||||
|
|
Loading…
Reference in New Issue