-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy patharithmetic.js
More file actions
58 lines (55 loc) · 1.73 KB
/
arithmetic.js
File metadata and controls
58 lines (55 loc) · 1.73 KB
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
const userInput = require('./userInput');
function getArray() {
const calcLength = userInput.getNumberInputWithPrompt('How many numbers do you want to perform an operation on?');
let numbersArray = [];
let operatorsArray = [];
let step;
let i;
for (step = 0, i = 0; step < calcLength; step++, i++) {
numbersArray[step]= userInput.getNumberInputWithPrompt(`Please enter number ${step+1}:`);
if (i < (calcLength-1)) {
operatorsArray[i]= userInput.getOperatorInputWithPrompt(`Please enter operator ${i+1}:`);
}
}
return [numbersArray, operatorsArray];
}
function calculateAnswer(array) {
const [numbers, operators] = array;
let answer = numbers[0];
let step;
let i;
for (step = 1, i = 0; step < numbers.length; step++, i++) {
switch (operators[i]) {
case '*':
answer *= numbers[step];
break;
case '+':
answer += numbers[step];
break;
case '-':
answer -= numbers[step];
break;
case '/':
answer /= numbers[step];
break;
case '%':
answer %= numbers[step];
break;
case '**':
answer **= numbers[step];
break;
default:
throw new Error(`Sorry, "${operators[i]}" is not a valid operator.`)
}
}
return answer;
}
exports.performOneArithmeticCalculation = function() {
const array = getArray();
try {
const answer = calculateAnswer(array);
console.log(`\nThe answer is ${answer}.`);
} catch (e) {
console.log(`\n${e.name}: ${e.message}`);
}
}