-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathrahuldahal_calculator.js
64 lines (56 loc) · 1.62 KB
/
rahuldahal_calculator.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
// Simple JS calculator script that will use browser's "prompt" to get user input
function init(){
const expression = getInput();
const extracted = extractOperatorAndOperands(expression)
if(extracted){
return performCalculation(extracted);
}
return "Invalid expression was provided";
}
function getInput(){
let userInput = window.prompt("enter any expression to calculate. Like, 2.5 + 3");
if(userInput){
return userInput.replace(/\s+/g, ""); // trimming the whitespace, if any
}
return "";
}
function extractOperatorAndOperands(expression){
// splits the expression into an array
if(!expression) return;
const availableOperators = ["+", "-", "*", "/"];
let isOperatorPresent = false;
const splittedExpression = [];
for(let operator of availableOperators){
if(expression.includes(operator)){
splittedExpression.push(operator);
splittedExpression.push(...expression.split(operator));
isOperatorPresent = true;
return splittedExpression;
}
}
if(!isOperatorPresent) return;
}
function performCalculation([operator, operandOne, operandTwo]){
if(!operandOne || !operandTwo){
return "Not enough operands were provided.";
}
operandOne = parseFloat(operandOne);
operandTwo = parseFloat(operandTwo);
switch(operator){
case "+":
return operandOne + operandTwo;
break;
case "-":
return operandOne - operandTwo;
break;
case "*":
return operandOne * operandTwo;
break;
case "/":
return operandOne / operandTwo;
break;
default:
throw new Error("Invalid operator received!!");
}
}
window.alert(init());