-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.ts
84 lines (71 loc) · 2.12 KB
/
index.ts
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
79
80
81
82
83
84
#!/usr/bin/env node
import inquirer from 'inquirer';
type TYPE_VARIABLE_NAMES = 'first_value' | 'second_value';
type TYPE_OPERATORS = '+'|'-'|'*'|'/'|'**'|'%';
type TYPE_IS_CONTINUE = 'Yes'|'No';
const ALL_OPERATORS:TYPE_OPERATORS[] = ['+','-','*','/','**','%'];
const IS_CONTINUE:TYPE_IS_CONTINUE[] = ['Yes','No'];
let firstValue:number | null;
let selectedOperator:TYPE_OPERATORS;
let secondValue:number | null;
async function askValue(variableName:TYPE_VARIABLE_NAMES){
const answer = await inquirer.prompt({
name: variableName,
type: 'input',
message: `Enter ${variableName.replace('_', ' ')}: `,
default(){
return 0;
},
validate: function (input:any) {
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:any){
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();