-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcalculator.js
More file actions
80 lines (72 loc) · 1.74 KB
/
calculator.js
File metadata and controls
80 lines (72 loc) · 1.74 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
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
"use strict";
var value = 0;
var changed = false;
var memValue = 0;
var lastValue = 0;
var operation = "none";
var inputDisplay;
function updateDisplay() {
inputDisplay.value = value;
}
function clearDisplay() {
inputDisplay.value = "0";
}
document.addEventListener("DOMContentLoaded", function (event) {
inputDisplay = document.getElementById('display');
// Events for number buttons
var numberMap = {
zero: 0, one: 1,
two: 2, three: 3,
four: 4, five: 5,
six: 6, seven: 7,
eight: 8, nine: 9
};
var handleNumberButtonClick = function (clickEvent) {
value = value * 10 + numberMap[clickEvent.target.id];
updateDisplay();
};
for (var numberButton in numberMap) {
document.getElementById(numberButton).onclick = handleNumberButtonClick;
}
// Events for operation buttons
document.getElementById('clear').onclick = function () {
value = 0;
memValue = 0;
lastValue = 0;
updateDisplay();
};
var operationCallback = function (clickEvent) {
if (changed === false) {
memValue = value;
value = 0;
}
operation = clickEvent.target.id;
changed = true;
updateDisplay();
};
['add', 'sub', 'mul', 'div'].forEach(function(operation) {
document.getElementById(operation).onclick = operationCallback;
});
document.getElementById('result').onclick = function () {
if (changed === true) {
lastValue = value;
value = memValue;
}
switch (operation) {
case 'add':
value += lastValue;
break;
case 'sub':
value -= lastValue;
break;
case 'mul':
value *= lastValue;
break;
case 'div':
value /= lastValue;
break;
}
changed = false;
updateDisplay();
};
});