-
Notifications
You must be signed in to change notification settings - Fork 0
/
calc.html
251 lines (243 loc) · 9.59 KB
/
calc.html
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
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
<html>
<head>
<meta charset="UTF-8">
<title>计算器</title>
</head>
<body>
<div class="calculator">
<label id="prefix" for="num"></label><input id="num" type="number" value="0"/><!-- 上次结果数字 -->
<select id="select-repr">
<option>Decimal (10)</option>
<option>Hex (16)</option>
<option>Binary (2)</option>
<option>Octal (8)</option>
<option>Slide in Bounds...</option>
</select>
<span id="fmt-stack"></span>
<div>
<table id="numPad"><!-- 0~9 --></table>
<il id="list-record"></il>
</div>
</div>
<script>
function helem(id) { return document.getElementById(id); }
function createHElem(tag, attrs) {
var e = document.createElement(tag);
if (attrs!=undefined) for (var k in attrs) e[k] = attrs[k];
return e;
}
var ePrefix = helem("prefix");
var eNumPad = helem("numPad");
var eNum = helem("num");
var eSelRepr = helem("select-repr");
var eRecords = helem("list-record");
var eStack = helem("fmt-stack");
for (var i=0; i<3+1; i++) {
var row = createHElem("tr");
for (var j=0; j<3; j++) {
var col = createHElem("td");
col.appendChild(createHElem("button", {textContent: String(i*3+j + 1/*firstBtn=1*/)}));
row.appendChild(col);
}
eNumPad.appendChild(row);
}
(function (op) {
op(3, 0, 'x'); op(3, 1, '0', "zero"); op(3, 2, '=');
})(function(i, j, text, title) {
if (title == undefined) title = "calc";
var e = eNumPad.children[i].children[j].firstChild;
e.textContent = text; e.title = title;
});
var refAcc = [0], refOperand = [0];
var refNum = refAcc;
var mode = "=", state=0, isDegreeUnit=false; // operator and read state
var stack = [], deftRedo=null/*-N means goto, N means do on res*/;
var opRecord = null; var opRecorded = [];
eNum.onchange = function() { refNum[0] = eNum.reprAsNumber; };
eNumPad.onclick = function(ev) {
var evt = ev.target;
if (evt.tagName != "BUTTON") return;
if (evt.title == "calc") {
var evtt = evt.textContent;
if (evtt == 'x') { refNum[0] = Math.floor(refNum[0] / 10); }
else if (evtt == '=') { onUpdate(); }
} else if (evt.title != "op") { refNum[0] = refNum[0]*10 + (evt.textContent-'0'); }
eNum.value = reprShow(refNum[0]);
};
"+ - * / id -@ % ** ~logN ~ln ~sin ~cos ~tan abs floor ceil round trunc rand INV DEGRAD RECO Redo DRedoIf DGotoIf Push Pop Shift Length Nth Plot Breakpoint".split(' ').forEach(function(oper, i) {
var hasInv = oper.startsWith('~'); // TODO: add bi-direction map for inv ops text maybe?
var eOper = createHElem("button", {
title: "op", // added ops
textContent: hasInv? oper.substr(1) : oper,
onclick: function(ev) { if (state==1) onUpdate()/*chain feat*/; mode = ev.target.textContent; onUpdate(); eNum.value = reprShow(refNum[0]); }
});
if (hasInv) { eOper.classList.add("inversabe"); }
var es = eNumPad.children;
es[i%es.length].appendChild(eOper);
});
function putsStack(is_dec) {
eStack.textContent = stack.join(',');;
if (is_dec) { eNum.value = reprShow(refAcc[0]); }
}
Math.radians = function(deg) { return deg*Math.PI/180; }
Math.degrees = function(deg) { return deg*180/Math.PI; }
function compose(g, f) {
return function h(x) { return g(f(x)); };
}
function onUpdate() { // state-machine with accumulator, un/bin-ary per operate based.
var mapNum = function(f) { refNum[0] = f(refNum[0]); };
var rad = function(angle) { return isDegreeUnit? Math.radians(angle) : angle; };
var deg = function(angle) { return isDegreeUnit? Math.degrees(angle) : angle; };
if (opRecord!=null && state!=1 && mode!="RECO") { // also for bin-ops
opRecord.push(mode); if (mode=="id") opRecord.push(refAcc[0]);
}
switch (mode) { // unary
case 'id'/*identity,itself*/: return;
case '-@': mapNum(n => -n); return;
case "DGotoIf":
if (deftRedo==null) { alert("Default-GotoIF requires deftRedo set"); return; }
if (refAcc[0] != 0) deftRedo = -(deftRedo +1);
return;
case "Redo":
var no = refAcc[0];
if (no < 0) { deftRedo = (-no) -1; }
else { redoRecorded(no); }
return;
case "DRedoIf":
if (deftRedo==null) { alert("Default-RedoIF requires deftRedo set with `id -Nth Redo`"); return; }
if (refAcc[0] != 0) redoRecorded(deftRedo);
return;
case "Push": stack.push(refAcc[0]); putsStack(false); return;
case "Pop": refAcc[0] = stack.pop()||0; putsStack(true); return;
case "Shift": refAcc[0] = stack.shift()||0; putsStack(true); return;
case 'sin': case 'cos': case 'tan':
mapNum(compose(Math[mode], rad));
return;
case '~sin': case '~cos': case '~tan':
mapNum(compose(deg, Math[mode.replace('~', 'a')]));
return;
case 'abs': mapNum(Math.abs); return;
case 'floor': mapNum(Math.floor); return;
case 'ceil': mapNum(Math.ceil); return;
case 'round': mapNum(Math.round); return;
case 'trunc': mapNum(Math.trunc); return;
case 'rand': refNum[0] = Math.random(); return;
case 'ln': mapNum(Math.log); return;
case '~ln': mapNum((n) => Math.E**n); return;
case "INV":
eNumPad.querySelectorAll(".inversabe").forEach(function (e) {
var s = e.textContent;
e.textContent = (s.startsWith('~'))? s.substr(1) : '~'+s;
});
return;
case "DEGRAD":
var n = refNum[0];
n = isDegreeUnit? Math.radians(n) : Math.degrees(n); refNum[0] = n;
isDegreeUnit = !isDegreeUnit;
eStack.textContent = isDegreeUnit? "Degree" : "Radian";
eNum.value = reprShow(n);
return;
case "RECO":
if (opRecord == null) { opRecord = []; }
else { opRecorded.push(opRecord); eRecords.appendChild(createHElem("li", {textContent: opRecord.join(" ")})); opRecord = null; }
return;
case "Length": refAcc[0] = stack.length; return;
case "Nth": refAcc[0] = stack[refAcc[0]]; return;
case "Plot": alert("TODO: impl with echar.js"); return;
case "Breakpoint":
var str = "redo#"+deftRedo+",acc="+refAcc+",operand="+refOperand;
str+=",#stk="+stack.length+",mode"+mode+",state"+state; // too bad..
alert(str); console.log((new Error).stack);
return;
}
if (state==0) { state=1; ePrefix.textContent = reprShow(refAcc[0])+mode; refOperand[0]=0; refNum=refOperand; return; } //< show oper req pad.
if (state==1&&opRecord!=null) { opRecord.push(refOperand[0]); }
var assign = function(op) { refAcc[0] = op(refAcc[0], refOperand[0]); };
switch (mode) { // binary
case '+': assign((a, b) => a+b); break; // TODO rewrite to ops[mode]; (and it's easy)
case '-': assign((a, b) => a-b); break;
case '*': assign((a, b) => a*b); break;
case '/': assign((a, b) => a/b); break;
case '%': assign((a, b) => a%b); break;
case '**': assign((a, b) => a**b); break;
case 'logN': assign((a, b) => Math.log(a)/Math.log(b)); break;
case '~logN': assign((c, b) => b**c); break;
}
state=0; mode = '='; ePrefix.textContent = ""; // reset to normal
refNum = refAcc;
if (deftRedo!=null&&deftRedo>=0) { redoRecorded(deftRedo); }
}
function redoRecorded(no) { // root of all evil (joke
no = Math.floor(no);
if (no >= opRecorded.length) { alert("op "+String(no)+" is not recorded yet"); return; }
var record = opRecorded[no];
for (var i=0; i<record.length; i++) {
var cmd = record[i];
if (cmd == "id") { i++; var t = record[i]; refAcc[0] = (t=="-Nth")? -(no +1) : t; continue; }
var oldDeft = deftRedo; //enclosed
mode = cmd; onUpdate();
if (deftRedo<0) { record = opRecorded[(-deftRedo) -1]; i = 0; deftRedo=oldDeft; continue; } //perf-critical
if (state==1) {
i++; refOperand[0] = record[i]; deftRedo=null;
onUpdate(); if (deftRedo<0) { record = opRecorded[(-deftRedo) -1]; i = 0; }
deftRedo=oldDeft;
}
}
}
function readIntMaybe(c) { var pn = parseInt(c); return (!isNaN(pn))? pn : c; };
eRecords.onclick = function() { createTextReprEditor(eRecords, function(ec) {
return Array.prototype.slice.call(ec.children).map(function(e) { return e.textContent; }).join('\n');
}, function(s) {
var ec = eRecords;
opRecorded = s.split('\n').map(function(t) { return t.split(' ').map(readIntMaybe); });
for (var i=0; i<opRecorded.length; i++) {
if (ec.children.length < i+1) { ec.appendChild(createHElem("li")); }
ec.children[i].textContent = opRecorded[i].join(' ');
}
}); };
eStack.onclick = function() { createTextReprEditor(eStack, function(ec) {
return ec.textContent;
}, function(s) {
stack = s.split(',').map(readIntMaybe);
eStack.textContent = stack.join(',');
}); };
function createTextReprEditor(ec, show, on_read) { // editor
var editor = createHElem("textarea", {placeholder: "Edit code by line..."});
editor.value = show(ec);
editor.onchange = function() {
on_read(editor.value);
editor.remove();
ec.hidden = false;
};
ec.parentNode.insertBefore(editor, ec);
ec.hidden = true;
};
//eNum#get_valueAsNumber, reprShow
(function() {
var aryBase = [10, 16, 2, 8];
var base = aryBase[eSelRepr.selectedIndex]; //enclosed
window.reprShow = function(n) { return n.toString(base); }
Object.defineProperty(eNum, "reprAsNumber", { get: function() { return parseInt(eNum.value, base); } });
var op = (function() {
var iSel = eSelRepr.selectedIndex;
if (0 <= iSel&&iSel <= 3) {
var vNum = eNum.reprAsNumber;
eNum.type = "number"; eNum.max = "";
base = aryBase[iSel];
eNum.value = reprShow(vNum);
} else if (iSel == 4) {
eNum.type = "range";
eNum.max = refNum[0];
}
});
eSelRepr.onchange = op; op();
})();
eNum.dispatchEvent(new Event("change"));
(function(s) { // TODO: switch to regexp-parse as map & call TextReprEditor ?
if (s == "") return;
opRecorded.push(s.split(",").map(readIntMaybe)); //special
eRecords.appendChild(createHElem("li", {textContent: opRecorded[0].join(" ")}));
refAcc[0]=0; mode="Redo"; onUpdate(); eNum.value = reprShow(refNum[0]); // TODO improv. reuse
})(window.location.search.substr(1));
</script>
</body>