-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.ts
More file actions
59 lines (47 loc) · 1.43 KB
/
index.ts
File metadata and controls
59 lines (47 loc) · 1.43 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
59
import { question } from "readline-sync";
type Operator = '+' | '-' | '*' | '/';
function main(): void {
const firstStr: string = question('Enter first number:\n');
const operator: string = question('Enter Operator:\n');
const secondStr: string = question('Enter second number\n');
const validInput: boolean = isNumber(firstStr) && isOperator(operator) && isNumber(secondStr);
if (validInput) {
// console.log('is valid.')
const firstNum: number = parseInt(firstStr)
const secondNum: number = parseInt(secondStr)
const result = calculate(firstNum, operator as Operator, secondNum)
console.log(result)
} else {
console.log('\ninvalid input\n')
main()
}
}
function calculate(firstNum: number, operator: Operator, secondNum: number) {
switch (operator) {
case '+':
return firstNum + secondNum;
case '-':
return firstNum - secondNum;
case '*':
return firstNum * secondNum;
case '/':
return firstNum / secondNum;
}
}
function isOperator(operator: string): boolean {
switch (operator) {
case '+':
case '-':
case '*':
case '/':
return true;
default:
return false
}
}
function isNumber(str: string): boolean {
const maybeNum = parseInt(str);
const isNum: boolean = !isNaN(maybeNum);
return isNum;
}
main()