-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathScriptCalculator.html
1306 lines (1202 loc) · 56.7 KB
/
ScriptCalculator.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
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<!DOCTYPE html>
<html>
<head>
<!--
Created by Míng on 2019-11-22.
Copyright © 2022 Míng <minglq.9@gmail.com>. Released under the MIT license.
-->
<!--
BUG:
- shortcuts for showing help, should be triggered any where?
TODO:
- CSS Nesting: https://developer.chrome.com/docs/css-ui/css-nesting
- replace all spaces to `␣` in $script
- replace all `␣` to spaces when calculate, copy/cut and share
- remove #underline?
- remove #reset?
- array, objct
- map, reduce, filter ...
- ewiki shortcuts config, and help
- refactor `calculate()` with RORO pattern
function find_func(args...) { ... return { name, args }; }
let { funcName, funcArgs } = find_func(args...);
- test cases: one group per page
- performance?
- ???: ignore trailing + - * / ((( ...
- layout
#see http://www.ruanyifeng.com/blog/2020/08/five-css-layouts-in-one-line.html
.container {
display: grid;
grid-template-columns: minmax(150px, 25%) 1fr;
}
- ???: invalid value
fa(a): a
fa() // <no-result> - undefined
fa(a): a * 1
fa() // NaN
NOTE:
- RexExp:
#see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions/Cheatsheet
x(?=y) // lookahead assertion
x(?!y) // negative lookahead assertion
(?<=y)x // lookbehind assertion
(?<!y)x // negative lookbehind assertion
-->
<title>ScriptCalculator by Míng</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<!-- meta name="viewport" content="width=device-width, user-scalable=no" / -->
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no" />
<style type="text/css" media="all">
/* the root element - https://developer.mozilla.org/en-US/docs/Web/CSS/:root */
:root {
--margin: 8px;
--space-l: 8px;
--space: 5px;
--top-height: 35px;
--right-width: 32%; /* 25% */
--ln-width: 20px;
}
html {
box-sizing: border-box;
font-family: monospace;
font-size: 13px;
}
*, *:before, *:after {
box-sizing: inherit;
font-family: inherit;
font-size: inherit;
}
html {
min-width: 1024px;
min-height: 256px;
overflow: scroll;
height: 100%;
padding: 0;
}
body {
height: calc(100% - var(--margin) * 2);
margin: var(--margin);
padding: 0;
overflow: hidden;
}
h1#background {
z-index: -1;
position: absolute;
font-size: 16vh;
margin-left: 2vw;
}
h1#background:after { /* disable browser finding by pseudo element */
content: "Script-\A Calculator\A by Míng";
white-space: pre;
color: ghostwhite;
}
h1#title {
display: inline-block;
margin: 0;
}
button {
font-size: 12px;
}
select:disabled {
text-decoration: line-through;
}
input {
vertical-align: middle;
}
a {
text-underline-position: under;
}
.underline {
text-decoration: underline;
text-underline-position: under;
}
#right {
width: var(--right-width);
margin: 0 0 0 var(--space-l);
position: relative;
}
#left {
width: calc(100% - var(--right-width) - var(--space-l));
margin: 0;
position: relative;
}
.container {
height: calc(100% - var(--top-height)/* - var(--space) * 2 */);
float: left;
display: inline-block;
line-height: 0;
}
#ruler {
pointer-events: none;
position: absolute;
right: 0px;
top: 0;
border-width: 0;
margin: 0;
width: 1px;
height: 100%;
background-color: gray;
opacity: 0.1;
}
#rulerHelper {
position: absolute;
top: 0;
right: 0;
width: revert;
height: revert;
/* remove left padding and border for calculating caret position */
padding-left: 0;
border-left-width: 0;
opacity: 0;
}
#script {
text-align: right;
border-radius: 5px;
}
#result {
padding-left: calc(var(--ln-width) + var(--space));
overflow-x: hidden;
border-radius: 5px;
}
#lineNumber {
pointer-events: none;
position: absolute;
left: 0;
top: 0;
width: var(--ln-width);
padding: var(--space) 1px;
border-color: transparent;
background-clip: padding-box;
background-color: #00000008;
color: darkgray;
text-align: right;
}
.code {
width: 100%;
height: 100%;
resize: none;
margin: 0;
padding: var(--space);
border-style: solid;
border-width: 0.5px;
border-color: gray;
background-color: transparent;
line-height: 18px; /* normal ~= 17.8 */
white-space: pre;
word-wrap: normal; /* for Safari */
overflow-x: scroll;
}
#script::-webkit-scrollbar,
#lineNumber::-webkit-scrollbar {
width: 0;
height: 0;
background: transparent;
}
</style>
</head>
<body>
<h1 id="background"></h1>
<!-- TODO: overflow: scroll / hide left; -->
<div id="top" style="height: var(--top-height); position: relative; overflow-x: scroll;">
<div style="position: absolute; left: 0; top: 0; padding: var(--space) 0;">
<h1 id="title">ScriptCalculator by <a target="_blank" href="https://iwill.im/">Míng</a></h1>
[ <a target="_blank" href="https://github.com/iwill/ScriptCalculator">GitHub</a>
| <a target="_blank" href="#eyJzY3JpcHQiOiIjIFNjcmlwdENhbGN1bGF0b3JcblxuXG4jIyBRdWljayBTdGFydCB8IOeugOWNleW6lOeUqFxuXG4xICsgMlxuLSAxXG4qIDVcbiogMTAlXG5cblxuIyMgVmFyaWFibGVzIHwg5Y%2BY6YePXG5cbiQgKyAkMyArIPCfkYbwn4%2B%2FICsgJCRcbj09IDEgKyAgMSArIDEgKyAxMFxuXG5hOiAxXG5iOiAyXG5hICsgYlxuXG5cbiMjIEZ1bmN0aW9ucyB8IOWHveaVsFxuXG5hZGQoeCwgeSk6IHggKyB5XG5hZGQoMSwgMilcblxuXG4jIyBKYXZhU2NyaXB0IHwg5Luj56CBXG5cbmBsb2NhdGlvbi5ocmVmLmxlbmd0aGBcbi0gYGxvY2F0aW9uLmhhc2gubGVuZ3RoYFxuXG4vLyBGaWJvbmFjY2lcbmYobik6IGBgYGpzXG5pZiAobiA8PSAwKSByZXR1cm4gMDsgICAgICAgXG5pZiAobiA8PSAyKSByZXR1cm4gMTsgICAgICAgXG5yZXR1cm4gZihuIC0gMSkgKyBmKG4gLSAyKTsgXG5gYGBcblxuZigwKVxuZigxKVxuZigyKVxuXG4kc3VtKC0zLCAtMSlcblxuXG4jIyBBbmQgbWFueSBtb3JlIHwg5pu05aSa5aW955So55qE5Yqf6IO95LuL57uN55yL6L%2BZ6YeMIPCfkYfwn4%2B%2FXG5cbi8vIGh0dHBzOi8vZ2l0aHViLmNvbS9pd2lsbC9TY3JpcHRDYWxjdWxhdG9yI3JlYWRtZVxuXG4ifQ%3D%3D-1000002-1000018">Demo</a>
| <a target="_blank" href="https://iwill.im/2022/07/08/script-calculator/">Help</a>
]
</div>
<div style="position: absolute; right: 0; top: 0; padding: var(--space) 0;">
<span id="errorsCount"></span>
decimal: <select id="decimalPlaces" onchange="sthChanged(event, this)">
<option value="-1">--</option><option value="0">0</option>
<option value="1">1</option><option value="2">2</option><option value="3">3</option><option value="4">4</option>
<option value="5">5</option><option value="6">6</option><option value="7">7</option><option value="8">8</option>
<option value="9">9</option><option value="10">10</option><option value="11">11</option><option value="12">12</option>
<option value="13">13</option><option value="14">14</option><option value="15">15</option><option value="16">16</option>
</select>
<!--
TODO: FixedPoint: <select id="fixedPoint" onchange="sthChanged(event, this)">
<option value="-1">--</option>
<option value="1">1</option><option value="2">2</option><option value="3">3</option><option value="4">4</option>
<option value="5">5</option><option value="6">6</option><option value="7">7</option><option value="8">8</option>
<option value="9">9</option><option value="10">10</option><option value="11">11</option><option value="12">12</option>
<option value="13">13</option><option value="14">14</option><option value="15">15</option><option value="16">16</option>
</select>
-->
rounding: <select id="roundingMethod" onchange="sthChanged(event, this)">
<option value="round">round</option><option value="floor">floor</option><option value="ceil">ceil</option>
</select>
<label>underline: <input type="checkbox" id="underline" onchange="underlineChanged(event, this)" /></label>
<button id="reset" onclick="resetClicked(event, this)">reset</button>
|
<button id="copy" onclick="copyOutputClicked(event, this)">copy</button>
<button id="share" onclick="shareShortenedURL(event, this)">share (beta)</button>
</div>
</div>
<div id="left" class="container">
<hr id="ruler" />
<textarea id="script" class="code" oninput="sthChanged(event, this)" onkeydown="shortcutsTriggered(event, this)" onscroll="scrollingChanged(event, this)"></textarea>
<pre id="rulerHelper" class="code"></pre>
</div>
<div id="right" class="container">
<textarea readonly id="result" class="code" onscroll="scrollingChanged(event, this)"></textarea>
<textarea readonly id="lineNumber" class="code" tabindex="-1" onscroll="scrollingChanged(event, this)"></textarea>
</div>
</body>
<script type="text/javascript">
"use strict";
(function onload(undefined) {
for (let method of ["round", "floor", "ceil"]) {
let _method = "_" + method;
Math[_method] = Math[method];
Math[method] = function(number, len) {
if (!len) {
return this[_method](number);
}
let pow = this.pow(10, this._floor(this.abs(len))); // !!!: `pow` supports negative numbers, but inaccurate
return len > 0 ? this[_method](number * pow) / pow : this[_method](number / pow) * pow;
};
}
Math.$sum = function(from, till) {
let length = vals.length;
if (from < 0) from = length + from;
else if (from === undefined) from = 0;
if (till < 0) till = length + till;
else if (till === undefined || till >= length) till = length - 1;
if (from > till) [from, till] = [till, from];
let sum = 0;
for (let i = from; i <= till; i++) {
sum += vals[i];
}
return sum;
};
Math.$avg = function(from, till) {
let length = vals.length;
if (from < 0) from = length + from;
else if (from === undefined) from = 0;
if (till < 0) till = length + till;
else if (till === undefined || till >= length) till = length - 1;
if (from > till) [from, till] = [till, from];
return this.$sum(from, till) / (till - from + 1);
};
Math.$min = function(from, till) {
let length = vals.length;
if (from < 0) from = length + from;
else if (from === undefined) from = 0;
if (till < 0) till = length + till;
else if (till === undefined || till >= length) till = length - 1;
if (from > till) [from, till] = [till, from];
let min = vals[from];
for (let i = from + 1; i <= till; i++) {
min = this.min(min, vals[i]);
}
return min;
};
Math.$max = function(from, till) {
let length = vals.length;
if (from < 0) from = length + from;
else if (from === undefined) from = 0;
if (till < 0) till = length + till;
else if (till === undefined || till >= length) till = length - 1;
if (from > till) [from, till] = [till, from];
let max = vals[from];
for (let i = from + 1; i <= till; i++) {
max = this.max(max, vals[i]);
}
return max;
};
Math.GR = Math.sqrt(1.25) - 0.5; // GoldenRatio
Math.Phi = Math.GR;
function isBuiltin(name) {
return !!Math[name] || globalThis[name] !== undefined || name === "undefined";
}
function isValidGlobalFunc(name) {
return [
"isFinite", "isNaN", "parseFloat", "parseInt",
"Number", "BigInt"
].includes(name);
}
function isValidBuiltinValue(name) {
return (Object.getOwnPropertyNames(Number).filter((key) => /^[A-Z][A-Z0-9_]*$/.test(key)).includes(name)
|| Object.getOwnPropertyNames(Math).filter((key) => /^[A-Z][A-Z0-9_]*$/.test(key)).includes(name)
|| ["Infinity", "NaN", "undefined"].includes(name));
}
function builtinValue(name) {
if (Object.getOwnPropertyNames(Number).filter((name) => /^[A-Z][A-Z0-9_]*$/.test(name)).includes(name)) {
return Number[name];
}
if (Object.getOwnPropertyNames(Math).filter((name) => /^[A-Z][A-Z0-9_]*$/.test(name)).includes(name)) {
return Math[name];
}
if (["Infinity", "NaN", "undefined"].includes(name)) {
return globalThis[name];
}
return undefined;
}
// let regExp = /^(?<name>[A-Za-z_][A-Za-z0-9_]*)\s*(?<args>\((\s*[A-Za-z_][A-Za-z0-9_]*\s*(,\s*[A-Za-z_][A-Za-z0-9_]*\s*)*)?\))\:/;
// tagged templates:
// RegExp.make`^[A-Za-z0-9_]*${"img"}` => /^[A-Za-z0-9_]*/img
// RegExp.make`^[A-Za-z0-9_]*${""}` => /^[A-Za-z0-9_]*/
// RegExp.make`^[A-Za-z0-9_]*` => /^[A-Za-z0-9_]*/
// #see https://stackoverflow.com/questions/12317049/how-to-split-a-long-regular-expression-into-multiple-lines-in-javascript/12317105#12317105
// #see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals
RegExp.make = (regExp, opts) => new RegExp(regExp.raw[0].replace(/( #.*|\s)/mg, ""), opts || "");
/// 7 Arithmetic, Remainder and Parentheses Operators
/// + - * / % ( )
/// 6 Comparison Operators
/// < <= > >= == !=
/// 7 Bitwise Operators
/// & | ~ ^ << >> >>>
/// 4 Logical Operators
/// && || ! ?:
/// Unary(Un), Binary(Bi) and Ternary(Ter)
const BI_TER_OPERATORS_START = RegExp.make`^(
[ \+ \- \* \/ \% ] | \*\* # NO ( and )
| [ \& \| \^ ] | \<\< | \>\> | \>\>\> # NO ~
| [ \< \> ] | \<\= | \>\= | \=\= | \!\=
| \&\& | \|\| | \? .* \: # NO !
| \#\d+ | \%\%
)`;
// const NOT_BI_TER_OPERATORS_START = RegExp.make`^(?!
// [ \+ \- \* \/ \% ] | \*\*
// | [ \& \| \^ ] | \<\< | \>\> | \>\>\>
// | [ \< \> ] | \<\= | \>\= | \=\= | \!\=
// | \&\& | \|\| | \? .* \:
// | \#\d+ | \%\%
// )`;
function tryCatch(f1, f2) {
try {
return f1();
}
catch (e) {
return f2(e);
}
}
function debugGroup(label, fn) {
label = label.replace(/%/g, "%%");
if (fn) {
console.group(label);
console.time(label);
fn();
console.timeEnd(label);
console.groupEnd(label);
}
}
function debugFunc(_args, src, fn) {
if (typeof src == "function") {
fn = src;
src = undefined;
}
let use_strict = (() => !this)();
if (use_strict) {
fn && fn();
}
else {
let path = [_args.callee.caller?.name, _args.callee.name].filter((x) => x).join(" > ");
if (src) {
path = `${src}.${path}`
}
console.debug(`func: ${path}`);
debugGroup(_args.callee.name, fn);
}
}
let $left = document.querySelector("#left");
let $ruler = document.querySelector("#ruler");
let $rulerHelper = document.querySelector("#rulerHelper");
$rulerHelper.remove();
let $script = $left.querySelector("#script");
let $right = document.querySelector("#right");
let $result = $right.querySelector("#result");
let $lineNumber = $right.querySelector("#lineNumber");
let $top = document.querySelector("#top");
let $decimalPlaces = $top.querySelector("#decimalPlaces");
// let $fixedPoint = $top.querySelector("#fixedPoint");
let $roundingMethod = $top.querySelector("#roundingMethod");
let $underline = $top.querySelector("#underline");
let copyOutput = "";
function commentIndex(line) {
let commentIndices = [
line.indexOf("//"),
(() => {
// TODO: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/matchAll#regexp.prototype.exec_and_matchall
// TODO: config.match(/(?<==)(INACTIVE|NOCODE|OPEN|TEMP|TEST|TODO:.+|UNSUPPORTED:.+)\s*$/g)[0]
// Array.from(str.matchAll(regexp), (m) => m[0]);
// Array.from(str.matchAll(regexp), (m) => `${regexp.lastIndex} ${m[0]}`);
let commentMatches = [...line.matchAll(/#+\d*\s*/g)];
if (commentMatches.length) {
let match = commentMatches[0];
if (!/#\d+/.test(match[0])) {
return match.index;
}
else if ((match = commentMatches[1])) {
return match.index;
}
}
return -1;
})()
].filter((x) => x >= 0);
let commentIndex = Math.min(...commentIndices);
return commentIndex == Infinity ? -1 : commentIndex;
}
function calculate() { debugFunc(arguments, function() {
/// prepare
let script = $script.value;
let trimmed = script.trim();
document.querySelector("title").innerText = trimmed.slice(0, trimmed.indexOf("\n")) || "ScriptCalculator by Míng";
// TODO: value.toLocaleString(undefined, {style: "decimal"/"currency"/"percent", currency: "USD"/"EUR"/"CNY", useGrouping: true});
// #see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/toLocaleString
// let display = value.toLocaleString();
/* TODO: lines [{
result: number / "" / "ERROR",
display: converted-number / "" / "ERROR",
lineNumber: number / "",
output: `code = value // comment`
}, ...] */
let result = [], lineNumber = [], output = [];
globalThis.funcs = {}, globalThis.vars = {}, globalThis.vals = [];
let multiLines = "", jsBlock;
let lines = script.split("\n");
for (let ln = 0; ln < lines.length; ln++) { let line = lines[ln]; debugGroup(`#${ln} \`${line}\``, function() {
let code, comment;
let varName, funcName, funcArgs;
let resToPercentage, resToBase;
let value, display;
try {
code = line.trim();
/// comments
let index = commentIndex(code);
if (index >= 0) {
comment = code.slice(index).trim();
code = code.slice(0, index).trim();
}
/// limit
if (vals.length >= 1000 && code.length) {
throw "too many calculations";
}
/// multiple lines: escape line-break by `\`
let hasEsc = code.endsWith("\\");
if (hasEsc || multiLines) {
multiLines += code.replace(/\\$/, "\t");
if (hasEsc) {
code = "";
}
else {
code = multiLines;
multiLines = "";
}
}
/// js blocks
let jsStarts = code.match(/^(.*)```\s*\w*\s*$/), jsEnds = code.endsWith("```");
let jsCode = false;
if (jsBlock === undefined) {
if (jsStarts) {
if (multiLines) {
throw `invalid blcok start \`\`\` in \`${line}\``;
}
jsBlock = jsStarts[1] || "";
code = "";
}
// NEVER
else if (jsEnds) {
throw `invalid block end \`\`\` in \`${line}\``;
}
// else NOT block
}
else { // if (jsBlock)
if (!jsEnds) {
if (jsStarts) {
throw `invalid block start \`\`\` in \`${line}\``;
}
jsBlock += "\t" + code;
code = "";
}
else { // if (jsEnds)
if (code != "```") {
throw `invalid block end \`\`\` in \`${line}\``;
}
code = jsBlock;
jsBlock = undefined;
jsCode = true;
}
}
if (code) {
if (!jsCode) {
/// replace inline js code with its returned value
// `js` -> eval(js)
code = code.replace(/`.*?`/g, (js) => {
// #see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/Function#:~:text=the%20Function%20constructor%20creates%20functions%20which%20execute%20in%20the%20global%20scope%20only
return (new Function(`"use strict"; return ${js.slice(1, -1)};`))();
});
console.debug(`01: code: ${code}`);
/// replace `+-×÷=` with `+-*/=`
code = code.replace(/+/g, "+").replace(/-/g, "-").replace(/×/g, "*").replace(/÷/g, "/").replace(/=/g, "=");
console.debug(`02: code: ${code}`);
/// replace single = with ==
code = code.replace(/(^|[^<!=>])=(?!=)/g, "$1==");
console.debug(`03: code: ${code}`);
/// validate symbols
if (/['"`\\\[\];]/g.test(code)) {
throw `invalid symbol in \`${line}\``;
}
// !!!: cannot use this regExp, because Safari and Swift does not support negative-lookbehind-assertion
// #see https://stackoverflow.com/a/2973495/456536
// let regExp = RegExp.make`
// (
// (?<! \w \s* \( \s* ) \{
// |
// \} (?! \s* \) )
// )
// `
// 匹配
// - 前边没有 `\w\(` 的 `{`
// 或
// - 后边没有 `)` 的 `}`
// 禁止 `{}` 符号,但允许 `f({})`
// 以便支持 RORO 参数,例如定义函数 `add({ a, b }): a + b`、调用函数 `add({ a: 4, b: 5 })`
if (/\}(?!\s*\))/g.test(code)) {
throw `invalid symbol in \`${line}\``;
}
/// prevent namespaces
// `xx.` || `.xx`
if (/\b[A-Za-z_][A-Za-z0-9_]*\s*\./g.test(code) || /\.\s*[A-Za-z_]/g.test(code)) {
throw `invalid dot in \`${line}\``;
}
}
/// find functions definition
// `fun({?[arg0[, argN]*]?}?):` // supports roro args https://www.tinyblog.dev/blog/2020-07-13-javascript-roro-pattern/
// `[A-Za-z_][A-Za-z0-9_]*` == `\b(?!\d)\w+\b`
let regExp = RegExp.make`
^ \s*
(?<name> \b[A-Za-z_][A-Za-z0-9_]* ) \s*
(?<args>
\(\s* \{? \s*
(
\b[A-Za-z_][A-Za-z0-9_]* \s*
(,\s* \b[A-Za-z_][A-Za-z0-9_]* \s* )*
)?
\}?\s* \)
) \s*
\: \s*
${/* opts: "" or "img" */""} # #see RegExp.make `;
let funcRes = code.match(regExp);
if (funcRes) {
funcName = funcRes.groups.name;
if (isBuiltin(funcName)) {
throw `invalid function definition in \`${line}\``;
}
funcArgs = funcRes.groups.args;
code = code.slice(funcRes.index + funcRes[0].length);
if (!code) {
throw `invalid function definition in \`${line}\``;
}
}
console.debug(`04: code: ${code}`);
/// find variables definition
// `(word-start) (no-number) words (word-end) colon`
let varRes = code.match(/^\b[A-Za-z_][A-Za-z0-9_]*\s*\:/);
if (varRes) {
varName = varRes[0].slice(0, -1).trim();
if (isBuiltin(varName)) {
throw `invalid variable definition in \`${line}\``;
}
code = code.slice(varRes.index + varRes[0].length).trim();
}
console.debug(`05: code: ${code}`);
if (!jsCode) {
/// auto insert `*` between number and other expr
code = code.replace(/(\d)\s+([A-Za-z_\$\(👆👆🏻👆🏼👆🏽👆🏾👆🏿])/g, "$1 * $2");
console.debug(`06: code: ${code}`);
/// validate functions and insert namespaces
// `(word-start) (no-number) words (word-end) [spaces] (left-parenthesis)`
code = code.replace(/\$?[A-Za-z_][A-Za-z0-9_]*\s*\(/g, (prefix) => {
let name = prefix.slice(0, -1).trim();
if (["constructor", "prototype", "toSource", "valueOf", "eval"].includes(name)) {
throw `invalid function \`${name}\` in \`${line}\``;
}
let namespace;
if (typeof funcs[name] == "function" || name == funcName) namespace = "funcs";
else if (typeof Math[name] == "function") namespace = "Math"; // just Math, no Number
else if (isValidGlobalFunc(name)) namespace = "globalThis";
else throw `invalid function \`${name}\` in \`${line}\``;
return `${namespace}.${name}(`;
});
console.debug(`07: code: ${code}`);
/// replace variables with values
// `(word-start) (no-number) words (word-end) (no- [spaces] (dot)(colon)(left-parenthesis))`
let regExp = RegExp.make`
\b
[A-Za-z_][A-Za-z0-9_]*
(?! \s* [\:\(]) # 后面有 ":" 的是 RORO 函数中的 argument label、有 "(" 的 function
\b
${"g"}`;
code = code.replace(/\b[A-Za-z_][A-Za-z0-9_]*(?!\s*[.:(])\b/g, (name) => {
if (funcName && new RegExp(`\\b${name}\\b`).test(funcArgs)) {
return name;
}
if (["constructor", "prototype", "toSource", "valueOf", "eval"].includes(name)) {
throw `invalid variable \`${name}\` in \`${line}\``;
}
let value = isValidBuiltinValue(name) ? builtinValue(name) : vars[name];
if (value === undefined) {
if (globalThis[name] !== undefined) {
throw `invalid variable \`${name}\` in \`${line}\``;
}
else {
value = name; // for `false`, and?
}
}
return `(${value})`;
});
console.debug(`08: code: ${code}`);
/// replace `$`, `$$`, ... and `$x` with values
// `dollar [numbers] (no-sum|avg|min|max)`
code = code.replace(/(\$+(?!sum|avg|min|max)|[👆👆🏻👆🏼👆🏽👆🏾👆🏿]+)(?!\d)/g, ($x) => {
let value = vals[vals.length - $x.match(/(\$|👆)/gu).length];
if (value === undefined) {
throw `invalid variable \`${name}\` in \`${line}\``;
}
return `(${value})`;
});
console.debug(`09: code: ${code}`);
code = code.replace(/\$\d+/g, ($x) => {
let index = Number($x.slice(1));
let value = vals[index];
if (value === undefined) {
throw `invalid variable \`${name}\` in \`${line}\``;
}
return `(${value})`;
});
console.debug(`10: code: ${code}`);
/// auto-prepend `$`, if `(line-start) (no-dollar) (no-words) (no-left-parenthesis)`
let prevRes = result[result.length - 1]; // if prev line has res, then prepend prev value - vars.$
// if ((prevRes || prevRes === 0 || prevRes === false) && code.length && code.match(/^([^!\(\w\$👆]|!=)/u))
if ((prevRes || prevRes === 0 || prevRes === false) && code.length && code.match(BI_TER_OPERATORS_START)) {
if (prevRes == "ERROR") {
throw `invalid result of prev line \`${prevRes}\` in \`${line}\``
}
code = `(${vars.$}) ${code}`;
}
console.debug(`11: code: ${code}`);
/// output percentage
resToPercentage = code.match(/%%\s*$/);
if (resToPercentage) {
code = code.slice(0, resToPercentage.index).trim();
}
console.debug(`12: code: ${code}`);
/// input percentage
code = code.replace(/(\d+(\.\d+)?)\s*%(?!\s*[\w\(])/g, (pct) => {
return `(${pct.replace(/\s*%/, "")} / 100)`;
});
console.debug(`13: code: ${code}`);
/// convert base of number system
let convert = code.match(/#\d+\s*$/);
if (convert) {
resToBase = Number(convert[0].slice(1));
if (resToBase < 2 || resToBase > 36) {
throw `invalid base \`${resToBase}\` in \`${line}\``
}
code = code.slice(0, convert.index).trim();
}
console.debug(`14: code: ${code}`);
}
/// eval
// if `jsCode`: requires `return` in `code`
// else: needs prepend `return` to `code` - `code` is math exp
let js = jsCode ? code : "return " + code; // `return` value
if (funcName) {
// return function as result
js = `return function ${funcName}${funcArgs} { ${js} }`; // `return` func
}
console.debug(`eval: ${js}`.replace(/%/g, "%%"));
// pass args funcs, vars and vals
let res = (new Function(`"use strict"; ${js}`))();
if (funcName) {
funcs[funcName] = res;
}
else {
value = res;
if (typeof value == "function") {
if (varName) {
funcName = varName;
funcArgs = "(...)";
funcs[funcName] = value;
varName = undefined;
value = undefined;
throw "WARNING: return func to var name is deprecated"
}
// !!!: DEPRECATED - js block returns a function
else if (value.name) {
funcName = value.name;
funcArgs = "(...)";
funcs[funcName] = value;
value = undefined;
throw "WARNING: return func to func name is deprecated"
}
}
}
} // end of `if (code)`
else {
value = undefined;
}
/// value, variables and display
let type = typeof value;
if (type == "number") {
let decimalPlaces = Number($decimalPlaces.value);
let rounding = decimalPlaces >= 0 && ((value, dp) => Math[$roundingMethod.value](value, dp));
if (rounding) {
value = rounding(value, decimalPlaces);
}
if (resToPercentage) {
let pctValue = value * 100;
if (rounding) {
pctValue = rounding(pctValue, decimalPlaces - 2);
}
display = pctValue + "%";
}
else if (resToBase && resToBase != 10) {
let prefix = (resToBase == 2) ? "0b" : (resToBase == 8) ? "0o" : (resToBase == 16) ? "0x" : "";
let suffix = !prefix && resToBase != 10 ? (" #" + resToBase) : "";
display = prefix + Math.abs(value).toString(resToBase).toUpperCase() + suffix;
if (value < 0) {
display = "-" + display;
}
}
else {
let absValue = Math.abs(value);
if (absValue < 1) {
let maxLength = 20; // limited by Number.toFixed()
if (absValue > Math.pow(10, - maxLength) && value.toString().indexOf("e") > 0) {
display = value.toFixed(maxLength);
}
}
else if (absValue > 1) {
if (value > Number.MAX_SAFE_INTEGER || value < Number.MIN_SAFE_INTEGER) {
display = value.toExponential();
}
// else if (value.toString().indexOf("e") > 0) {
// display = value.toLocaleString("fullwide", { useGrouping: false });
// }
}
}
}
else if (type == "bigint") {
if (resToBase && resToBase != 10) {
let prefix = (resToBase == 2) ? "0b" : (resToBase == 8) ? "0o" : (resToBase == 16) ? "0x" : "";
let suffix = !prefix && resToBase != 10 ? (" #" + resToBase) : "";
display = prefix + Math.abs(value).toString(resToBase).toUpperCase() + suffix;
if (value < 0) {
display = "-" + display;
}
}
else {
display = `BigInt: ${value}`
}
}
else if (type == "string") {
display = `String: ${value}`
}
else {
if (resToPercentage || resToBase) {
throw `invalid conversion \`${resToPercentage || resToBase}\` in \`${line}\``;
}
if (type == "boolean") {
// nothing to do
}
else {
if (varName) {
throw `invalid variable \`${varName}\` in \`${line}\``;
}
else if (value !== undefined) {
throw `invalid result \`${value}\` in \`${line}\``;
}
}
}
/// log
let log = value ? `${code} = ${display || value}` : (`${code} ${comment || ""}`.trim() || "<empty-line>");
console.log("res: " + log.replace(/%/g, "%%"));
}
catch(e) {
console.warn((e + "").replace(/%/g, "%%"));
if (vars._enable_error) {
value = `${e}`.startsWith("WARNING") ? e : "ERROR: " + e;
}
else {
value = `${e}`.startsWith("WARNING") ? "WARNING" : "ERROR";
}
}
/// result
result.push(display || value);
let text;
let type = typeof value;
if (["number", "bigint", "boolean", "string"].includes(type)) {
vals.push(value);
vars.$ = value;
if (varName) {
vars[varName] = value;
}
lineNumber.push(vals.length - 1);
text = `${code.replace(/\s*funcs\.\s*/g, "")} = ${display || value} ${comment || ""}`;
}
else {
lineNumber.push("·");
text = funcName ? `${funcName}${funcArgs}: ${code} ${comment || ""}` : comment;
}
output.push(text?.trim().replace(/ ?\t/g, " \\\n"));
});} // end of `for (let ln = 0; ln < lines.length; ln++)`
/// output
// let fixed = result.map((name, index) => name ? Number(name).toFixed(2) : name);
$result.value = result.join("\n");
$lineNumber.value = lineNumber.join("\n");
// 1. join lines with `\n`, 2. remove parentheses with single number, 3. remove leading space before `/\\$/mg`, 4. remove too many `\n`
copyOutput = output.join("\n").replace(/\(\s*(\d*\.?\d*)\s*\)/g, "$1").replace(/^ +(?=\\$)/mg, "").replace(/\n{3,}/g, "\n\n");
let lnLength = vals.length.toString().length;
document.documentElement.style.setProperty("--ln-width", Math.max(2, lnLength) * 10 + "px");
let errorsCount = result.reduce((obj, res) => {
if (typeof res == "string") {
if (res.startsWith("ERROR")) obj.errors += 1;
else if (res.startsWith("WARNING")) obj.warnings += 1;
}
return obj;
}, { errors: 0, warnings: 0 });
let text = [
errorsCount.errors && "errors: "+ errorsCount.errors,
errorsCount.warnings && "warnings: " + errorsCount.warnings,
].filter((res) => res).join(", ");
document.querySelector("#errorsCount").innerText = text ? text + " |" : null;
});}
function updateScriptStyle() {
$script.classList[$underline.checked ? "add" : "remove"]("underline");
}
function updateBorderStyle() {
let urlTooLoong = location.href.length > 65536;
$script.style.outlineColor = $result.style.outlineColor = (urlTooLoong ? "red" : null);
// TODO: navigator.userAgentData
if (navigator.userAgent.indexOf("Safari") >= 0) {
$script.style.outlineStyle = $result.style.outlineStyle = (urlTooLoong ? "solid" : null);
}
if (urlTooLoong) {
console.error(`url is too loong: ${location.href.length}!`);
}
}
function updateRuler() {
if (vars._enable_ruler == false) {
$ruler.style.visibility = "hidden";
return;
}
let script = $script.value;
let start = $script.selectionStart;
let end = script.indexOf("\n", start);
if (end < 0) {
end = script.length;
}
$rulerHelper.innerText = script.slice(start, end);
$left.appendChild($rulerHelper);
let width = $rulerHelper.offsetWidth;
let space = (parseFloat(window.getComputedStyle($script).getPropertyValue("padding-right"))
+ parseFloat(window.getComputedStyle($script).getPropertyValue("border-right-width")));
$ruler.style.visibility = width <= space ? "hidden" : "visible";
// `+ 1` (caret width) to avoid overlapping the ruler and caret
$ruler.style.right = Math.ceil(width + 1) + "px"
$rulerHelper.remove();
}
let jsSerializeToHash = false;
const selectionPlaceholder = 1000000;
// TODO: `-?` and `.?` instead of `-` to backward compatible with `start|end`
const selectionRegExp = /-?(\d+).?(\d+)$/;
// const selectionRegExp = /-(\d+)-(\d+)$/;
// base64 -> encode("+/=") -> "%2B%2F%3D"
// #see https://developer.mozilla.org/en-US/docs/Glossary/Base64#the_unicode_problem
// #see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/encodeURIComponent#encoding_for_content-disposition_and_link_headers
const encode = (x) => btoa(unescape(encodeURIComponent(x))).replace(/[\+\/=]/g, encodeURIComponent);
const decode = (x) => decodeURIComponent(escape(atob(x.replace(/%(?:2B|2F|3D)/g, decodeURIComponent))));
function serializeToHash() { debugFunc(arguments, function() {
let json = {};
if ($decimalPlaces.selectedIndex) {
json.decimalPlaces = $decimalPlaces.selectedIndex;
}
if ($roundingMethod.selectedIndex) {
json.roundingMethod = $roundingMethod.selectedIndex;
}
if ($underline.checked) {
json.underline = true;
}