Skip to content

Commit edad889

Browse files
committed
Add composite example
1 parent 80c4703 commit edad889

File tree

1 file changed

+44
-0
lines changed

1 file changed

+44
-0
lines changed

JavaScript/2-composite.js

Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
1+
'use strict';
2+
3+
class Product {
4+
constructor(name, price) {
5+
this.name = name;
6+
this.productPrice = price;
7+
}
8+
9+
get price() {
10+
return this.productPrice;
11+
}
12+
}
13+
14+
class Purchase {
15+
constructor(name, ...collection) {
16+
this.name = name;
17+
this.collection = collection;
18+
}
19+
20+
get price() {
21+
let price = 0;
22+
for (const item of this.collection) {
23+
price += item.price;
24+
}
25+
return price;
26+
}
27+
}
28+
29+
// Usage
30+
31+
const p1 = new Product('Laptop', 1500);
32+
const p2 = new Product('Mouse', 25);
33+
const p3 = new Product('Keyboard', 100);
34+
const p4 = new Product('HDMI cable', 10);
35+
const electronics = new Purchase('Electronics', p1, p2, p3, p4);
36+
37+
const p5 = new Product('Bag', 50);
38+
const p6 = new Product('Mouse pad', 5);
39+
const textile = new Purchase('Textile', p5, p6);
40+
41+
const purchase = new Purchase('Work kit', electronics, textile);
42+
43+
console.dir(purchase, { depth: null });
44+
console.log(`Total is ${purchase.price}`);

0 commit comments

Comments
 (0)