-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathCompositePattern.js
More file actions
68 lines (56 loc) · 1.71 KB
/
Copy pathCompositePattern.js
File metadata and controls
68 lines (56 loc) · 1.71 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
"use strict";
/**
* Composite Pattern - treat a group of objects uniformly. It composes objects into
* tree structures to represent part as well as whole hierarchy.
*
* Example - A person can be a single person and a person can have many persons under
* him/her, for example his/her children. In this case, composite pattern can be
* used.
*
*/
class Person {
constructor(name, age) {
this.name = name
this.age = age
this.children = []
}
registerChild(child) {
this.children.push(child);
}
disownChild(index) {
this.children.splice(index, 1);
}
listDescendents() {
let currentPerson = this;
return (function recursiveGet(person, level) {
console.log("|" + "-".repeat(level*2) + " Current Person: " + person.name + ", Level: " + level);
if (person.children.length > 0) {
for (let eachDescendent of person.children) {
recursiveGet(eachDescendent, level + 1);
}
}
})(currentPerson, 1)
}
}
console.log("Tim is a person and has two sons, Tom and Teddy");
var tim = new Person("Tim", 65);
var tom = new Person("Tom", 32);
var ted = new Person("Teddy", 28);
tim.registerChild(tom);
tim.registerChild(ted);
console.log("Tom is married and has a daughter, Cheryl");
var cheryl = new Person("Cheryl", 5);
tom.registerChild(cheryl);
console.log("--- Descendents of Tim");
tim.listDescendents();
console.log("--- Descendents of Tom");
tom.listDescendents();
console.log("We forgot to add the great grandfather, Joe");
var joe = new Person("Joe", 90);
joe.registerChild(tim);
joe.listDescendents();
console.log("Teddy gets married and gets a son, Paul");
var paul = new Person("Paul", 1);
ted.registerChild(paul);
console.log("Now the hierarchy gets even bigger");
joe.listDescendents();