-
Notifications
You must be signed in to change notification settings - Fork 9
/
Copy pathrecursion-practice.js
51 lines (43 loc) · 1.25 KB
/
recursion-practice.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
let categories = [
{ id: 'animals', 'parent': null },
{ id: 'mammals', 'parent': 'animals' },
{ id: 'cats', 'parent': 'mammals' },
{ id: 'dogs', 'parent': 'mammals' },
{ id: 'chihuahua', 'parent': 'dogs' },
{ id: 'labrador', 'parent': 'dogs' },
{ id: 'persian', 'parent': 'cats' },
{ id: 'siamese', 'parent': 'cats' }
]
let makeTree = (categories, parent) => {
// each node is created every time makeTree is called
let node = {}
// c is each object in the category array
categories
.filter(c => c.parent === parent)
.forEach(c =>
node[c.id] = makeTree(categories, c.id))
return node
}
let result = makeTree(categories, null)
console.log(JSON.stringify(result, null, 2))
// First filter the `parent` which is `null`
// Then pass object the matching object(s) to `forEach`:
// { id: 'animals', 'parent': null }
// node['animals'] = makeTree(categories, 'animals')
// which then filters the categories object on instances
// where caches.parent === 'animals'
// each node gets attached to its parent
// {
// "animals": {
// "mammals": {
// "cats": {
// "persian": {},
// "siamese": {}
// },
// "dogs": {
// "chihuahua": {},
// "labrador": {}
// }
// }
// }
// }