-
Notifications
You must be signed in to change notification settings - Fork 0
/
hazyCalculator.js
60 lines (48 loc) · 1.42 KB
/
hazyCalculator.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
function isSkippedValue(value) {
return !value
}
function isNumericValue(value) {
return !isNaN(value)
}
function isNothingValue(value) {
return value === null
}
function isAcceptableValue(value) {
const operators = ['+', '-', '*', '/']
return typeof value === Number || operators.includes(value)
}
function performCalculationStep(firstOperand, operator, secondOperand) {
switch (operator) {
case '+':
return firstOperand + secondOperand
case '-':
return firstOperand - secondOperand
case '*':
return firstOperand * secondOperand
case '/':
return firstOperand / secondOperand
default:
throw new Error('Invalid input!')
}
}
function calculate(calculationSteps) {
let total
let operator
calculationSteps.forEach(nextCalculationStep => {
if (!isAcceptableValue(nextCalculationStep)) {
throw new Error('Invalid input!')
}
if (isNothingValue(total) && isNumericValue(nextCalculationStep)) {
total = Number(nextCalculationStep)
} else if (isNothingValue(operator) && !isSkippedValue(nextCalculationStep)) {
operator = nextCalculationStep
} else if (isNumericValue(nextCalculationStep)) {
total = performCalculationStep(total, operator, Number(nextCalculationStep))
operator = null
} else if (!isSkippedValue(nextCalculationStep)) {
throw new Error('Invalid input!')
}
})
return total
}
module.exports = calculate