Skip to content

Commit 285f1ad

Browse files
committed
Add composite pattern example for solution
1 parent 3990650 commit 285f1ad

File tree

1 file changed

+44
-0
lines changed

1 file changed

+44
-0
lines changed

src/Composite/Book/index.ts

+44
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
1+
export interface Component {
2+
getPrice(): number;
3+
}
4+
5+
class Product implements Component {
6+
constructor(private name: string, private price: number) {}
7+
8+
getPrice(): number {
9+
return this.price;
10+
}
11+
}
12+
13+
class Box implements Component {
14+
private items: Component[] = [];
15+
16+
constructor(private name: string, private packagingCost: number) {}
17+
18+
addItem(item: Component) {
19+
this.items.push(item);
20+
}
21+
removeItem(item: Component) {
22+
this.items = this.items.filter((i) => i !== item);
23+
}
24+
25+
getPrice(): number {
26+
return (
27+
this.packagingCost +
28+
this.items.reduce((acc, item) => acc + item.getPrice(), 0)
29+
);
30+
}
31+
}
32+
33+
const smallProduct = new Product("Small Product", 10);
34+
const smallBox = new Box("Small Box", 1);
35+
36+
smallBox.addItem(smallProduct);
37+
38+
const bigProduct = new Product("Big Product", 100);
39+
const bigBox = new Box("Big Box", 5);
40+
41+
bigBox.addItem(bigProduct);
42+
bigBox.addItem(smallBox);
43+
44+
console.log(bigBox.getPrice());

0 commit comments

Comments
 (0)