-
Notifications
You must be signed in to change notification settings - Fork 46
/
index.js
67 lines (61 loc) · 1.74 KB
/
index.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
$(function() {
var result = 0;
var operation = null;
var currentEntry = 0;
var prevEntry = 0;
updateScreen(result);
$(".button").on("click", function(e) {
var pressed = $(this).data("value");
if(pressed === "C") {
result = 0;
currentEntry = 0;
updateScreen(currentEntry);
} else if(pressed === "+/-") {
currentEntry *= -1;
updateScreen(currentEntry);
} else if(pressed === "%") {
currentEntry /= 100;
updateScreen(currentEntry);
} else if(pressed === ".") {
if(currentEntry === 0) {
currentEntry = pressed;
} else {
currentEntry += pressed.toString();
}
updateScreen(currentEntry);
} else if(isOperator(pressed)) {
prevEntry = currentEntry;
operation = pressed;
currentEntry = "";
$(".result span").html(operation);
} else if(isNum(pressed)) {
if(currentEntry === 0) {
currentEntry = pressed;
} else {
currentEntry += pressed.toString();
}
updateScreen(currentEntry);
} else if(pressed === "=") {
currentEntry = compute(prevEntry, currentEntry, operation);
operation = null;
updateScreen(currentEntry);
}
});
});
function updateScreen(display) {
$(".result span").html(display);
}
function isNum(value) {
return !isNaN(value);
}
function isOperator(value) {
return value === "÷" || value === "x" || value === "-" || value === "+";
}
function compute(prev, current, operation) {
prev = parseFloat(prev);
current = parseFloat(current);
if(operation === "+") return prev + current;
else if(operation === "-") return prev - current;
else if(operation === "x") return prev * current;
else if(operation === "÷") return prev / current;
}