-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbonus.js
60 lines (50 loc) · 1.26 KB
/
bonus.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
const rs = require("readline-sync");
function askQuestion() {
const question = rs.question("Please enter an operation: ");
return question;
}
function executeOperation(operation) {
const array = operation.split(" ");
if (array.length !== 3) {
console.log(
"Wrong input. Please enter the operation in the format: 'number operator number'."
);
return false;
}
const num1 = Number(array[0]);
const operator = array[1];
const num2 = Number(array[2]);
if (isNaN(num1) || isNaN(num2)) {
console.log("This is not a number. Please enter a number.");
return false;
}
let result;
switch (operator) {
case "/":
if (num2 === 0) {
console.log("Error. Please choose a number higher than 0.");
return false;
}
result = num1 / num2;
break;
case "*":
result = num1 * num2;
break;
case "-":
result = num1 - num2;
break;
case "+":
result = num1 + num2;
break;
default:
console.log(`Wrong operator. Choose between "/", "*", "-", or "+".`);
return false;
}
console.log(`The result is: ${result}`);
return true;
}
let validInput = false;
while (!validInput) {
const question = askQuestion();
validInput = executeOperation(question);
}