-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
89 lines (71 loc) · 1.57 KB
/
index.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
78
79
80
81
82
83
84
85
86
87
88
89
class StackCalculator {
constructor() {
this.stack = []
}
putValue(value) {
this.stack.push(value)
}
getValue() {
return this.stack.pop()
}
peekValue() {
return this.stack[this.stack.length - 1]
}
clear() {
this.stack = []
}
divide() {
const divisor = this.getValue()
const diviend = this.getValue()
const result = diviend / divisor
this.putValue(result)
return result
}
multiply() {
const multiplicand = this.getValue()
const multiplier = this.getValue()
const result = multiplicand * multiplier
this.putValue(result)
return result
}
}
class SafeCalculator {
constructor(calculator) {
this.calculator = calculator
}
putValue(value) {
this.calculator.putValue(value)
}
getValue() {
return this.calculator.getValue()
}
peekValue() {
return this.calculator.peekValue()
}
clear() {
this.calculator.clear()
}
divide() {
const divisor = this.peekValue()
if (divisor === 0) {
throw new Error('Division by 0!')
}
this.calculator.divide()
}
multiply() {
return this.calculator.multiply()
}
}
const stackCalculator = new StackCalculator()
const safeCalculator = new SafeCalculator(stackCalculator)
stackCalculator.putValue(2)
stackCalculator.putValue(3)
console.log(stackCalculator.multiply())
safeCalculator.putValue(2)
console.log(safeCalculator.multiply())
stackCalculator.putValue(0)
console.log(stackCalculator.divide())
safeCalculator.clear()
safeCalculator.putValue(4)
safeCalculator.putValue(0)
console.log(safeCalculator.divide())