Skip to content

Commit 79b8ada

Browse files
committed
Recursion tree
1 parent 6f263c3 commit 79b8ada

File tree

2 files changed

+66
-0
lines changed

2 files changed

+66
-0
lines changed

src/recursion-tree/recursion-tree.js

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
// Recursion - function that calls itself until it doesn't
2+
3+
// Make relation tree:
4+
export const getAnimalsTree = (categories, parent) => {
5+
let node = {};
6+
categories
7+
.filter((c) => c.parent === parent)
8+
.forEach((c) => (node[c.id] = getAnimalsTree(categories, c.id)));
9+
return node;
10+
};
Lines changed: 56 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,56 @@
1+
import { getAnimalsTree } from "./recursion-tree";
2+
3+
describe("Recursion tree", () => {
4+
test("Recursion tree", () => {
5+
expect(
6+
getAnimalsTree(
7+
[
8+
{ id: "animals", parent: null },
9+
{ id: "mammals", parent: "animals" },
10+
{ id: "cats", parent: "mammals" },
11+
{ id: "dogs", parent: "mammals" },
12+
{ id: "persian", parent: "cats" },
13+
{ id: "siamese", parent: "cats" },
14+
{ id: "labrador", parent: "dog" },
15+
],
16+
null
17+
)
18+
).toStrictEqual({
19+
animals: {
20+
mammals: {
21+
cats: {
22+
persian: {},
23+
siamese: {},
24+
},
25+
dogs: {},
26+
},
27+
},
28+
});
29+
});
30+
test("Recursion tree", () => {
31+
expect(
32+
getAnimalsTree(
33+
[
34+
{ id: "animals", parent: null },
35+
{ id: "mammals", parent: "animals" },
36+
{ id: "cats", parent: "mammals" },
37+
{ id: "dogs", parent: "mammals" },
38+
{ id: "persian", parent: "cats" },
39+
{ id: "siamese", parent: "cats" },
40+
{ id: "labrador", parent: "dog" },
41+
],
42+
null
43+
)
44+
).toStrictEqual({
45+
animals: {
46+
mammals: {
47+
cats: {
48+
persian: {},
49+
siamese: {},
50+
},
51+
dogs: {},
52+
},
53+
},
54+
});
55+
});
56+
});

0 commit comments

Comments
 (0)