-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
81 lines (67 loc) · 1.76 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
const readline = require('readline-sync');
function welcomeMessage() {
console.log('Welcome to the Calculator');
}
function checkOp(maybeOp) {
if (maybeOp != '+' && maybeOp != '-' && maybeOp != '*' && maybeOp != '/') {
console.log('Your input is in the wrong format.');
} else {
return maybeOp;
}
}
function checkNum(maybeNum) {
if (isNaN(maybeNumber)) {
// It didn't work - we have NaN.
} else {
// It worked - we have a number.
}
}
function getStrInput(prompt) {
console.log(prompt);
return readline.prompt();
}
function getNumInput(prompt) {
console.log(prompt);
return parseFloat(readline.prompt());
}
function getOp(prompt) {
let maybeOp = getStrInput('Please enter an operator:');
return checkOp(maybeOp);
}
function getNoOfNos(op) {
return getNumInput('How many numbers would you like to ' + op + ' ?');
}
function getNos(noOfNos) {
let nos = [];
for (let i = 1; i <= noOfNos; i++) {
nos.push(getNumInput('Please enter number ' + i + ' :'));
}
return nos
}
function doCalculation(noOfNos, op, numbers) {
let answer = numbers[0]
for (let i = 1; i < noOfNos; i++) {
if (op === '+') {
answer += numbers[i];
} else if (op === '-') {
answer -= numbers[i];
} else if (op === '*') {
answer *= numbers[i];
} else if (op === '/') {
answer /= numbers[i];
}
}
return answer
}
function calculator() {
let op = getOp();
let noOfNos = getNoOfNos(op);
let numbers = getNos(noOfNos);
let ans = doCalculation(noOfNos, op, numbers);
console.log('The answer is ' + ans);
}
welcomeMessage();
// console.log(getOp());
while (true) {
calculator();
}