File tree 1 file changed +44
-0
lines changed
1 file changed +44
-0
lines changed Original file line number Diff line number Diff line change
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 ( ) ) ;
You can’t perform that action at this time.
0 commit comments