-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcomposite.js
More file actions
69 lines (55 loc) · 1.25 KB
/
composite.js
File metadata and controls
69 lines (55 loc) · 1.25 KB
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
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
class Component {
constructor(name) {
this.name = name
}
add(component) {
throw new Error('Method `add()` should be overridden')
}
remove(component) {
throw new Error('Method `remove()` should be overridden')
}
display(depth = 0) {
throw new Error('Method `display()` should be overridden')
}
}
class Leaf extends Component {
display(depth = 0) {
console.log(`${' '.repeat(depth)}- ${this.name}`)
}
}
class Composite extends Component {
constructor(name) {
super(name)
this.children = []
}
add(component) {
this.children.push(component)
}
remove(component) {
const index = this.children.indexOf(component)
if (index !== -1) {
this.children.splice(index, 1)
}
}
display(depth = 0) {
console.log(`${' '.repeat(depth)}+ ${this.name}`)
for (const child of this.children) {
child.display(depth + 2)
}
}
}
const root = new Composite('Root element')
const node1 = new Composite('Node 1')
node1.add(new Leaf('Leaf 1.1'))
node1.add(new Leaf('Leaf 1.2'))
const node2 = new Composite('Node 2')
node2.add(new Leaf('Leaf 2.1'))
root.add(node1)
root.add(node2)
root.display()
// + Root element
// + Node 1
// - Leaf 1.1
// - Leaf 1.2
// + Node 2
// - Leaf 2.1