-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcal.ts
64 lines (55 loc) · 1.43 KB
/
cal.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
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)
{
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();