-
Notifications
You must be signed in to change notification settings - Fork 0
/
script.js
51 lines (51 loc) · 1.44 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
class Calculator {
constructor(expr, res) {
this.exprEl = expr
this.resEl = res
this.clear()
}
clear() {
this.exprEl.value = ''
this.resEl.value = ''
}
delete() {
this.exprEl.value = this.exprEl.value.slice(0, -1)
}
appendNumber(number) {
this.exprEl.value += number
}
appendOperation(operation) {
this.exprEl.value += operation
}
compute() {
try {
const eres = eval(this.exprEl.value);
this.resEl.value = eres;
} catch (error) {
this.resEl.value = 'ERR';
}
}
}
const numberButtons = document.querySelectorAll('[data-number]')
const operationButtons = document.querySelectorAll('[data-operation]')
const equalsButton = document.querySelector('[data-equals]')
const deleteButton = document.querySelector('[data-delete]')
const expressionInput = document.getElementById('expr');
const resultInput = document.getElementById('res');
const calculator = new Calculator(expressionInput, resultInput)
numberButtons.forEach(button => {
button.addEventListener('click', () => {
calculator.appendNumber(button.innerText)
})
})
operationButtons.forEach(button => {
button.addEventListener('click', () => {
calculator.appendOperation(button.innerText)
})
})
equalsButton.addEventListener('click', button => {
calculator.compute()
})
deleteButton.addEventListener('click', button => {
calculator.delete()
})