forked from vladilenm/SOLID_javascript
-
Notifications
You must be signed in to change notification settings - Fork 0
/
2_O.js
77 lines (63 loc) · 1.06 KB
/
2_O.js
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
70
71
72
73
74
75
76
77
// Open Close Principle
class Shape {
area() {
throw new Error('Area method should be implemented')
}
}
class Square extends Shape {
constructor(size) {
super()
this.size = size
}
area() {
return this.size ** 2
}
}
class Circle extends Shape {
constructor(radius) {
super()
this.radius = radius
}
area() {
return (this.radius ** 2) * Math.PI
}
}
class Rect extends Shape {
constructor(width, height) {
super()
this.width = width
this.height = height
}
area() {
return this.width * this.height
}
}
class Triangle extends Shape {
constructor(a, b) {
super()
this.a = a
this.b = b
}
area() {
return (this.a * this.b) / 2
}
}
class AreaCalculator {
constructor(shapes = []) {
this.shapes = shapes
}
sum() {
return this.shapes.reduce((acc, shape) => {
acc += shape.area()
return acc
}, 0)
}
}
const calc = new AreaCalculator([
new Square(10),
new Circle(1),
new Circle(5),
new Rect(10, 20),
new Triangle(10, 15)
])
console.log(calc.sum())