-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.js
More file actions
52 lines (46 loc) · 1.54 KB
/
app.js
File metadata and controls
52 lines (46 loc) · 1.54 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
let userInput = "";
let lastInput = "";
let display = document.getElementById("output");
let calcObj = document.getElementById('calculator');
let calcBtns = calcObj.querySelectorAll("input[type='button']");
for (let btn of calcBtns){
btn.addEventListener("click", function() {
if (btn.getAttribute('class') == 'extra-action') {
if (this.value == '=') {
let result = calculate(userInput);
if (result != undefined) {
updateDisplay(result);
}
} else if (this.value == 'x') {
userInput = userInput.toString();
userInput = userInput.slice(0, userInput.length - 1); //remove last input
updateDisplay(userInput);
}
} else {
if (validInput([lastInput, this.value])){
userInput += this.value;
lastInput = this.value;
updateDisplay(userInput);
}
}
});
}
function calculate(input) {
try {
return eval(input);
} catch(e) {
alert("Invalid Operation: simple arithmetic operations only");
console.log(e);
}
}
function validInput(inputs) {
let operators = ['+', '-', '*', '/'];
[lastInput, currentInput] = inputs;
if (operators.includes(lastInput) && operators.includes(currentInput))
return false;
return true;
}
function updateDisplay(value) {
userInput = value;
display.innerHTML = userInput;
}