-
Notifications
You must be signed in to change notification settings - Fork 1
/
script.js
86 lines (85 loc) · 2.63 KB
/
script.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
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
const add = (a,b)=>a+b;
const subtract = (a,b) => a-b;
const multiply = (a,b)=>a*b;
const divide = (a,b)=>a/b;
let number1 = 0;
let number2 = 0;
let operator = '+';
const operate = (a,b,op) =>{
switch(op){
case '+': return add(a,b);
case '-': return subtract(a,b);
case '*': return multiply(a,b);
case '/': return divide(a,b);
default : return 'Operation Error';
}
}
let isOperatorActive = false;
let isEqualDone = false;
let previousOperatorNode = undefined;
const display = document.querySelector('#display');
const clear = document.querySelector('#clr');
const equal = document.querySelector('#equal');
equal.addEventListener('click',(e)=>{
number2 = Number(display.textContent);
const answer = operate(number1,number2,operator);
display.textContent = answer;
number1 = 0;
number2 = 0;
operator = '+';
isEqualDone = true;
if(previousOperatorNode != undefined){
previousOperatorNode.style.backgroundColor = 'rgb(77, 74, 74)';
}
previousOperatorNode = undefined;
});
clear.addEventListener('click',()=>{
display.textContent = 0;
});
const numbers = document.querySelectorAll('.number');
let n = numbers.length;
for (let i = 0;i<n;i++){
numbers[i].addEventListener('click',(e)=>{
let currentDisplay = 0;
if(isEqualDone){
display.textContent = 0;
isEqualDone = false;
}
if(isOperatorActive){
currentDisplay = 0;
isOperatorActive = false;
}
else{
currentDisplay = Number(display.textContent);
}
const t = Number(e.target.textContent);
const newNumber = t + currentDisplay*10;
display.textContent = newNumber;
});
}
let previousOperator = undefined;
const operators = document.querySelectorAll('.operator');
n = operators.length;
for (let i = 0;i<n;i++){
operators[i].addEventListener('click',(e)=>{
operator = e.target.textContent;
if(previousOperator === undefined){
previousOperator = operator;
}
isOperatorActive = true;
if(number1 != 0){
number2 = Number(display.textContent);
number1 = operate(number1,number2,previousOperator);
display.textContent = number1;
}else{
number1 = Number(display.textContent);
display.textContent = 0;
}
e.target.style.backgroundColor = 'black';
if(previousOperatorNode != undefined){
previousOperatorNode.style.backgroundColor = 'rgb(77, 74, 74)';
}
previousOperator = operator;
previousOperatorNode = e.target;
});
}