-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathscript.js
115 lines (90 loc) · 2.43 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
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
"use strict";
var Calculator = function (container) {
this.container = container;
this.init();
};
Calculator.prototype = {
init: function () {
document.myCalculators = document.myCalculators || [];
document.myCalculators.push(this);
this.createLayout();
this.str = 0;
this.updateDisplay();
},
input: function (input) {
if (this.str)
this.str += input;
else
this.str = input;
this.updateDisplay();
},
output: function (input) {
return this.validate() || eval(this.str);
},
validate: function () {
var str = this.str;
var reg = /[^1-9,0,*,/,\-,+,%, ,(,)]/g;
var result = str.match(reg);
if (result || str.endsWith("+") || str.endsWith("-") || str.endsWith("*") || str.endsWith("/")) {
return "Invalid: " + (result || "End of character.");
}
},
updateDisplay: function (result) {
document.getElementById("c-header").innerHTML = result || this.str;
},
sum() {
this.updateDisplay(this.output());
},
clear: function () {
this.str = 0;
this.updateDisplay();
},
createLayout: function () {
var cont = document.getElementById(this.container);
cont.className += " gr-calculator";
cont.appendChild(this.createHeader());
cont.appendChild(this.createBody());
},
createHeader: function () {
var cHeader = document.createElement("div");
cHeader.innerHTML = '<div id="c-header" class="c-header">Display</div>';
return cHeader;
},
createButton (text, i) {
var button = document.createElement("button");
button.innerHTML = text;
var buttonObserver = this.buttonObserver;
button.addEventListener("click", function () { buttonObserver(this.innerHTML) });
return button;
},
buttonObserver (a) {
var currentCalc = document.myCalculators[0];
if (a == "C") {
currentCalc.clear();
}
else if (a == "=") {
currentCalc.sum();
}
else {
currentCalc.input(a);
}
},
createBody () {
var cBody = document.createElement("div");
cBody.id = "c-body";
cBody.className = "c-body";
for (var i = 0; i < 10; i++) {
cBody.appendChild(this.createButton(i));
}
cBody.appendChild(this.createButton("+"));
cBody.appendChild(this.createButton("-"));
cBody.appendChild(this.createButton("*"));
cBody.appendChild(this.createButton("/"));
cBody.appendChild(this.createButton("="));
cBody.appendChild(this.createButton("("));
cBody.appendChild(this.createButton(")"));
cBody.appendChild(this.createButton("C"));
return cBody;
}
};
var a = new Calculator("myCalculator");