Created
May 1, 2021 14:06
-
-
Save parasg1999/ab8b0d7193de7d29ac1836264ecdf6d3 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// const readlineSync = require('readline-sync') | |
import { question } from 'readline-sync'; | |
type Operator = '+' | '-' | '*' | '/'; | |
const fNum: string = question('Enter first number: '); | |
const operator: string = question('Enter operator: '); // + , - , * , / | |
const sNum: string = question('Enter second number: '); | |
// console.log(fNum, operator, sNum); | |
let isInputValid : boolean = isNumber(fNum) && isOperator(operator) && isNumber(sNum); | |
let firstNumber = parseInt(fNum); | |
let secondNumber = parseInt(sNum); | |
if(isInputValid) { | |
const result: number = calculate(firstNumber, operator as Operator, secondNumber); | |
console.log(result); | |
} else { | |
console.log('Invalid input'); | |
} | |
function calculate(num1 : number, op: Operator, num2: number) : number { | |
switch(op) { | |
case '+': | |
return num1+num2; | |
case '-': | |
return num1-num2; | |
case '*': | |
return num1*num2; | |
case '/': | |
return num1/num2; | |
} | |
} | |
// console.log(isOperator(operator)); | |
function isNumber (value: string) : boolean { | |
let num = parseInt(value, 10); | |
let notNumber = isNaN(num); | |
return !notNumber; | |
} | |
function isOperator (value: string): boolean { | |
switch(value) { | |
case '+': | |
case '-': | |
case '*': | |
case '/': | |
return true; | |
default: | |
return false; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment