-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
71 lines (71 loc) · 1.91 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
#!/usr/bin/env node
import inquirer from 'inquirer';
const ALL_OPERATORS = ['+', '-', '*', '/', '**', '%'];
const IS_CONTINUE = ['Yes', 'No'];
let firstValue;
let selectedOperator;
let secondValue;
async function askValue(variableName) {
const answer = await inquirer.prompt({
name: variableName,
type: 'input',
message: `Enter ${variableName.replace('_', ' ')}: `,
default() {
return 0;
},
validate: function (input) {
const value = parseFloat(input);
if (!isNaN(value)) {
return true;
}
else {
return 'You need to provide a number';
}
}
});
switch (variableName) {
case 'first_value':
firstValue = await getNumber(answer.first_value);
case 'second_value':
secondValue = await getNumber(answer.second_value);
default: ;
}
}
async function getNumber(value) {
value = parseFloat(value);
if (!isNaN(value)) {
return value;
}
else {
return null;
}
}
async function askOperator() {
const answer = await inquirer.prompt({
name: 'operator',
type: 'list',
message: 'Select an Operator',
choices: ALL_OPERATORS
});
selectedOperator = answer.operator;
}
async function runCalculator() {
await askValue('first_value');
await askOperator();
await askValue('second_value');
let result = eval(`${firstValue} ${selectedOperator} ${secondValue}`);
console.log(`${firstValue} ${selectedOperator} ${secondValue} = ${result}`);
let answer = await inquirer.prompt({
name: 'is_continue',
type: 'list',
message: 'Do you want to continue?',
choices: IS_CONTINUE
});
if (answer.is_continue == 'Yes') {
await runCalculator();
}
else {
process.exit(1);
}
}
await runCalculator();