-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.js
50 lines (40 loc) · 1007 Bytes
/
main.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
function calculate(inputValue){
// https://regex101.com
const expression = /\+|\-|\*|\//;
const numbers = inputValue.split(expression);
const numberA = parseInt(numbers[0]);
const numberB = parseInt(numbers[1]);
const operation = inputValue.match(expression);
if (Number.isNaN(numberA) || Number.isNaN(numberB) || operation === null){
updateResult('Operation not recognized');
return;
}
const calculator = new Calculator();
calculator.add(numberA);
let result;
switch(operation[0]){
case '+':
result = calculator.add(numberB);
break;
case '-':
result = calculator.substract(numberB);
break;
case '*':
result = calculator.multiply(numberB);
break;
case '/':
if (numberB === 0){
updateResult('Cannot divide by zero');
return;
}
result = calculator.divide(numberB);
break;
}
updateResult(result);
}
function updateResult(result){
const element = document.getElementById('result');
if(element){
element.innerText = result;
}
}