forked from lvandeve/logicemu
-
Notifications
You must be signed in to change notification settings - Fork 0
/
logicemu.js
executable file
·18207 lines (16531 loc) · 692 KB
/
logicemu.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
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
/*
LogicEmu
Copyright (c) 2018-2021 Lode Vandevenne
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
// Generic JavaScript utilities for LogicEmu
var LogicEmuUtils = (function() {
// exported functions are assigned to result which will be returned by this self invoking anonymous function expression
var result = {};
var doNotAddToParent = 'doNotAddToParent';
var makeElement = function(tag, opt_parent) {
var parent = opt_parent || document.body;
var el = document.createElement(tag);
if(parent != doNotAddToParent) parent.appendChild(el);
return el;
};
result.makeElement = makeElement;
var makeElementAt = function(tag, x, y, opt_parent) {
var el = makeElement(tag, opt_parent);
el.style.position = 'absolute';
el.style.left = '' + Math.floor(x) + 'px';
el.style.top = '' + Math.floor(y) + 'px';
return el;
};
result.makeElementAt = makeElementAt;
var makeAbsElement = function(tag, x, y, w, h, opt_parent) {
var el = makeElement(tag, opt_parent);
el.style.position = 'absolute';
el.style.left = '' + Math.floor(x) + 'px';
el.style.top = '' + Math.floor(y) + 'px';
el.style.width = '' + Math.floor(w) + 'px';
el.style.height = '' + Math.floor(h) + 'px';
return el;
};
result.makeAbsElement = makeAbsElement;
var removeElement = function(el) {
if(!el) return;
var p = el.parentNode;
if(p && p.contains(el)) {
p.removeChild(el);
}
};
result.removeElement = removeElement;
var makeDiv = function(x, y, w, h, opt_parent) {
var el = makeAbsElement('div', x, y, w, h, opt_parent);
return el;
};
result.makeDiv = makeDiv;
var styleUIElementBorder = function(el) {
el.style.border = '1px solid #888';
};
result.styleUIElementBorder = styleUIElementBorder;
var highlightUIElementBorder = function(el, opt_color) {
var color = opt_color || 'black';
el.style.border = '2px solid ' + color;
};
result.highlightUIElementBorder = highlightUIElementBorder;
var styleUIElement = function(el, opt_smallbutton) {
styleUIElementBorder(el);
el.style.height = '20px';
el.style.width = '80px';
el.style.margin = '1px';
el.style.padding = '0';
el.style.backgroundColor = '#eee';
el.style.cursor = 'pointer';
el.style.boxShadow = '0.5px 0.5px #aaa';
el.style.textAlign = 'center';
el.style.boxSizing = 'border-box';
el.style.font = '400 13px Arial';
if (opt_smallbutton == 1) {
el.style.width = '20px';
}
if (opt_smallbutton == 2) {
el.style.width = '40px';
}
if (opt_smallbutton == 3) {
el.style.width = '60px';
}
};
var makeUIElement = function(tag, opt_parent, opt_smallbutton) {
var el = makeElement(tag, opt_parent);
styleUIElement(el, opt_smallbutton);
return el;
};
result.makeUIElement = makeUIElement;
var makeUISpacer = function(width, el) {
var s = makeElement('span', el);
s.style.width = width + 'px';
s.style.display = 'inline-block';
};
result.makeUISpacer = makeUISpacer;
var makeInternalButton = function(title, parent, x, y, fun) {
var button = makeUIElement('button', parent);
button.style.position = 'absolute';
button.style.left = x + 'px';
button.style.top = y + 'px';
button.innerText = title;
button.onclick = function() {
fun();
};
};
result.makeInternalButton = makeInternalButton;
//bind a single argument to a function
var bind = function(f, arg) {
var args = Array.prototype.slice.call(arguments, 1);
var result = function() {
return f.apply(this, args.concat(Array.prototype.slice.call(arguments)));
};
result.bound_f = f; // to be able to "extract" the original function out of it for debugging and by code
result.bound_arg = arg; // to be able to "extract" the original function out of it for debugging and by code
return result;
};
result.bind = bind;
// deep clone
var clone = function(obj) {
// Handle the 3 simple types, and null or undefined
if(null == obj || 'object' != typeof obj) return obj;
// Handle Array
if(obj instanceof Array) {
var copy = [];
for(var i = 0, len = obj.length; i < len; i++) {
copy[i] = clone(obj[i]);
}
return copy;
}
// Handle Object
if (obj instanceof Object) {
var copy = new obj.constructor(); //This makes it also have the correct prototype
for(var attr in obj) {
if(obj.hasOwnProperty(attr)) copy[attr] = clone(obj[attr]);
}
return copy;
}
throw new Error('Cloning this object not supported.');
};
result.clone = clone;
// only shallow clone array
var cloneArray = function(arr) {
var result = [];
for(var i = 0; i < arr.length; i++) {
result[i] = arr[i];
}
return result;
};
result.cloneArray = cloneArray;
var textHasAt = function(text, pos, sub) {
return text.substr(pos, sub.length) == sub;
};
result.textHasAt = textHasAt;
var mergeMaps = function(a, b) {
var c = clone(a);
for(var k in b) {
if(b.hasOwnProperty(k)) c[k] = b[k];
}
return c;
};
result.mergeMaps = mergeMaps;
var getCGIParameterByName = function(name, opt_url) {
var url = opt_url || window.location.href;
name = name.replace(/[\[\]]/g, "\\$&");
var regex = new RegExp("[?&]" + name + "(=([^&#]*)|&|#|$)");
var results = regex.exec(url);
if (!results) return null;
if (!results[2]) return '';
return decodeURIComponent(results[2].replace(/\+/g, " "));
};
result.getCGIParameterByName = getCGIParameterByName;
// like getCGIParameterByName, but with # instead of ?
var getFragmentParameterByName = function(name, opt_url) {
var url = opt_url || window.location.href;
name = name.replace(/[\[\]]/g, "\\$&");
var regex = new RegExp("[#&]" + name + "(=([^&#]*)|&|#|$)");
var results = regex.exec(url);
if (!results) return null;
if (!results[2]) return '';
return decodeURIComponent(results[2].replace(/\+/g, " "));
};
result.getFragmentParameterByName = getFragmentParameterByName;
// sets fragment with this value. Supports only max 1 fragment in total.
var setFragment = function(name, value) {
if(history && history.replaceState) {
// using history to NOT have history!
// with history.replaceState, this avoids it creating a new back-button entry each time you update the URL fragment
// reason for not storing this as history: it doesn't actually work because there's nothing here that handles pressing the back button,
// and, it's quite annoying if this app creates a long back button history so you can't go back to the real previous website you came from.
// if I do implement history button at some point, maybe it should only go back to index, but not through all circuits visited to avoid that annoyance
if(!value) {
if(window.location.hash) history.replaceState(undefined, undefined, '#');
} else {
history.replaceState(undefined, undefined, '#' + name + '=' + value);
}
} else {
// fallback for browsers that don't support history.replaceState
if(!value) {
if(window.location.hash) window.location.hash = '';
} else {
window.location.hash = '#' + name + '=' + value;
}
}
};
result.setFragment = setFragment;
var clearFragment = function() {
setFragment('', null);
};
result.clearFragment = clearFragment;
// removes queries and fragments
var getUrlWithoutQueries = function() {
var url = window.location.href;
var q = url.indexOf('?');
if(q >= 0) url = url.substr(0, q);
q = url.indexOf('#');
if(q >= 0) url = url.substr(0, q);
return url;
};
result.getUrlWithoutQueries = getUrlWithoutQueries;
var clearSelection = function() {
if(document.selection) {
document.selection.empty();
} else if(window.getSelection) {
window.getSelection().removeAllRanges();
}
};
result.clearSelection = clearSelection;
var localStorageSupported = function() {
try {
return 'localStorage' in window && window['localStorage'] !== null;
} catch(e) {
return false;
}
};
result.localStorageSupported = localStorageSupported;
//remember user settings locally (note that this is all fully local, nothing gets sent to any server)
var setLocalStorage = function(data, name) {
if(!localStorageSupported()) return;
localStorage[name] = data ? data : '';
};
result.setLocalStorage = setLocalStorage;
//note: returns values as strings, e.g. booleans will get string 'true' or 'false'
var getLocalStorage = function(name, opt_default) {
if(!localStorageSupported()) return opt_default;
if(localStorage[name] == undefined) return opt_default;
return localStorage[name];
};
result.getLocalStorage = getLocalStorage;
// Replacement for setInterval that hopefully works a bit better in modern background-tab-throttling browsers
// This is not attempting to circumvent background throttling, but instead trying to prevent the tab hanging
// when coming back to it and browsers may make it do all the missed intervals at once...
// This tries to combine timeouts with the desired timing, with requestAnimationFrame which has better guarantees that
// the browser will not do any more frames when the tab is in the background (rather than collect more and more "debt" of expensive updates it will try to call all at once)
// TODO: this may require updating every now and then as browsers change their behavior of background tabs
var setIntervalSafe = function(fun, msec) {
var clear = false;
var fun2 = function() {
if(clear) return;
fun();
// requestAnimationFrame is used because this one will not run in background tab, which is better than being throttled in background tab but then do all updates at once when the tab becomes foreground, causing slow computation
// NOTE: this may add an extra delay to the desired msec, of 1/60th of a second probably
requestAnimationFrame(function() {
// setTimeout is used becuase this one uses the desired milliseconds unlike requestAnimationFrame.
window.setTimeout(fun2, msec);
});
};
window.setTimeout(fun2, msec);
var clearfun = function() {
clear = true;
};
return clearfun;
};
result.setIntervalSafe = setIntervalSafe;
var clearIntervalSafe = function(id) {
id(); // id is actually a function.
};
result.clearIntervalSafe = clearIntervalSafe;
// See explanation at setIntervalSafe
var setTimeoutSafe = function(fun, msec) {
// NOTE: this is very unreliable in modern browsers, especially when tabs come back from background
var time0 = (new Date()).getTime(); // milliseconds since epich
var canceled = false;
// test: disable the requestAnimationFrame step: makes it faster for small msec amounts, but however
// causes risk of causing browser to hang when this tab was in background and gets enabled again only later
// TODO: find way that allows fast updates yet works correctly (= doesnt' consume resources just like the browser wants) in background tabs. Unfortunately requestAnimationFrame is the only thing that guarantees nice behavior but is limited to 60fps... so using requestAnimationFrame only every so many ticks (of the update() function) could work
//var requestAnimationFrame = function(fun){fun();};
requestAnimationFrame(function() {
if(canceled) return;
var time1 = (new Date()).getTime();
var d = time1 - time0;
msec -= d;
if(msec > 0) {
window.setTimeout(function() {
if(canceled) return;
fun();
}, msec);
} else {
fun();
}
});
return function() {
canceled = true;
};
};
result.setTimeoutSafe = setTimeoutSafe;
var clearTimeoutSafe = function(id) {
id(); // id is actually a function.
};
result.clearTimeoutSafe = clearTimeoutSafe;
// warning: does not validate input
var normalizeCSSColor = function(css) {
// only has named colors used somewhere in here.
if(css == 'black') css = '#000000';
if(css == 'white') css = '#ffffff';
if(css == 'red') css = '#ff0000';
if(css == 'green') css = '#00ff00';
if(css == 'blue') css = '#0000ff';
if(css == 'yellow') css = '#00ffff';
if(css.length == 4) {
css = '#' + css[1] + css[1] + css[2] + css[2] + css[3] + css[3];
}
return css;
};
var parseCSSColor = function(css) {
css = normalizeCSSColor(css);
var r = parseInt(css.substr(1, 2), 16);
var g = parseInt(css.substr(3, 2), 16);
var b = parseInt(css.substr(5, 2), 16);
return [r, g, b];
};
var formatCSSColor = function(rgb) {
var r = rgb[0].toString(16);
var g = rgb[1].toString(16);
var b = rgb[2].toString(16);
if(r.length == 1) r = '0' + r;
if(g.length == 1) g = '0' + g;
if(b.length == 1) b = '0' + b;
return '#' + r + g + b;
};
var formatCSSColorAlpha = function(rgba) {
return 'rgba(' + rgba[0].toString(10) + ', ' + rgba[1].toString(10) + ', ' +
rgba[2].toString(10) + ', ' + (rgba[3] / 255.0) + ')';
};
// slightly darkens the color
var darkenColor = function(css, amount) {
amount = amount || 16;
var rgb = parseCSSColor(css);
rgb[0] = Math.max(0, rgb[0] - amount);
rgb[1] = Math.max(0, rgb[1] - amount);
rgb[2] = Math.max(0, rgb[2] - amount);
return formatCSSColor(rgb);
};
// slightly brightens the color
var brightenColor = function(css, amount) {
amount = amount || 16;
var rgb = parseCSSColor(css);
rgb[0] = Math.min(255, rgb[0] + amount);
rgb[1] = Math.min(255, rgb[1] + amount);
rgb[2] = Math.min(255, rgb[2] + amount);
return formatCSSColor(rgb);
};
// alpha given in range 0.0-1.0
var addAlpha = function(css, alpha) {
var rgb = parseCSSColor(css);
return formatCSSColorAlpha([rgb[0], rgb[1], rgb[2], alpha * 255]);
};
result.addAlpha = addAlpha;
// either darkens or lightens the color, depending on how light it is
var twiddleColor = function(css, amount) {
amount = amount || 16;
var rgb = parseCSSColor(css);
var lightness = 0.21 * rgb[0] + 0.72 * rgb[1] + 0.07 * rgb[2];
return lightness < 128 ? brightenColor(css, amount) : darkenColor(css, amount);
};
result.twiddleColor = twiddleColor;
var negateColor = function(css) {
var rgb = parseCSSColor(css);
rgb[0] = (255 - rgb[0]);
rgb[1] = (255 - rgb[1]);
rgb[2] = (255 - rgb[2]);
return formatCSSColor(rgb);
};
result.negateColor = negateColor;
var negateLigntness = function(css) {
var rgb = parseCSSColor(css);
var r = rgb[0];
var g = rgb[1];
var b = rgb[2];
var mm = Math.min(Math.min(r, g), b) + Math.max(Math.max(r, g), b);
r = 255 - mm + r;
g = 255 - mm + g;
b = 255 - mm + b;
return formatCSSColor([r, g, b]);
};
result.negateLigntness = negateLigntness;
var averageColor = function(css0, css1) {
var rgb0 = parseCSSColor(css0);
var rgb1 = parseCSSColor(css1);
rgb0[0] = ((rgb0[0] + rgb1[0]) >> 1);
rgb0[1] = ((rgb0[1] + rgb1[1]) >> 1);
rgb0[2] = ((rgb0[2] + rgb1[2]) >> 1);
return formatCSSColor(rgb0);
};
result.averageColor = averageColor;
// e,g, code point 0x1f600 returns smile emoji.
var unicode_to_utf16 = function(code_point) {
var result = '';
if (code_point < 0x10000) {
result += String.fromCharCode(code_point);
} else if (code_point <= 0x10FFFF) {
result += String.fromCharCode((code_point >> 10) + 0xD7C0);
result += String.fromCharCode((code_point & 0x3FF) + 0xDC00);
} else {
result += String.fromCharCode(0xFFFD); // replacement character code
}
return result;
};
result.unicode_to_utf16 = unicode_to_utf16;
return result;
}());
var util = LogicEmuUtils;
// for now, export this very often used utility functions directly
var bind = util.bind;
var makeDiv = util.makeDiv;
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
// Mathematics for the "ALU" component
// Mostly integer math. If LogicEmuMath.supportbigint is true, functions require type BigInt as input and output, else regular JS numbers.
var LogicEmuMath = (function() {
// exported functions/fields are assigned to result which will be returned by this self invoking anonymous function expression
var result = {};
var supportbigint = !!window.BigInt;
result.supportbigint = supportbigint;
// Make integer of the relevant type: BigInt if supported, JS number otherwise.
// Most of the math here will use BigInt if available, JS number otherwise.
// If JS supports BigInt, then, between JS number and BigInt:
// - the following operators work the same (but support larger values for bigInt): almost all, including +, %, <=, <<, &, **, etc...
// - the following operators work differently: / becomes integer division
// - the following things are not supported, resulting in an exception: mixing JS nubmer with BigInt for any operation except comparisons; using Math.#### functions on BigInt.
var B = supportbigint ? window.BigInt : function(i) { return i; };
result.B = B;
// the notation 0n, 1n, 3n, ... cannot be used, because if browser doesn't support BigInt,
// it'll give parsing error on decimal number ending with n.
var n0 = B(0); result.n0 = n0;
var n1 = B(1); result.n1 = n1;
var n2 = B(2); result.n2 = n2;
var n3 = B(3); result.n3 = n3;
var n4 = B(4); result.n4 = n4;
var n5 = B(5); result.n5 = n5;
var n6 = B(6); result.n6 = n6;
var n7 = B(7); result.n7 = n7;
var n10 = B(10); result.n10 = n10;
var n11 = B(11); result.n11 = n11;
var n13 = B(13); result.n13 = n13;
var n15 = B(15); result.n15 = n15;
var n17 = B(17); result.n17 = n17;
var gcd = function(a, b) {
if(a < 0) a = -a;
if(b < 0) b = -b;
for(;;) {
if(b == 0) return a;
var o = a % b;
a = b;
b = o;
}
};
result.gcd = gcd;
var lcm = function(a, b) {
var g = gcd(a, b);
if(g == 0) return n0;
return intdiv(a, g) * b;
};
result.lcm = lcm;
// error cases: returns 0 if result would be infinity
var truncdiv = function(a, b) {
if(b == 0) return n0;
if(supportbigint) return a / b;
var result = a / b;
return (result < 0) ? Math.ceil(result) : Math.floor(result);
};
result.truncdiv = truncdiv;
// error cases: returns 0 if result would be infinity
var floordiv = function(a, b) {
if(b == 0) return n0;
if(!supportbigint) return Math.floor(a / b);
var result = a / b;
if((a < 0) != (b < 0)) {
var m = result * b;
if(m != a) result--;
}
return result;
};
result.floordiv = floordiv;
// only for positive integers, so slightly faster due to less checks.
var intdiv = function(a, b) {
if(b == 0) return n0;
if(!supportbigint) return Math.floor(a / b);
return a / b;
};
// a modulo b, matching floored division (not matching truncated division, like the % operation does)
var mod = function(a, b) {
var negb = (b < 0);
if(negb) b = -b;
var nega = (a < 0);
if(nega) a = -a;
a %= b;
if(nega) { a = (b - a) % b; } // not the most optimal implementation, but made to easily work for both Number and BigInt
if(negb) a = -a;
return a;
};
result.mod = mod;
// in case BigInt is not supported, this function helps to support shifting up to 2**53 instead of just up to 2**31
var rshift1 = supportbigint ? function(n) { return n >> n1; } : function(n) { return Math.floor(n / 2); };
// like left shift, but designed to also work with more than 31 bits in case BigInt is not supported in the browser
var lshift = supportbigint ? function(n, s) { return n << s; } : function(n, s) { return n * ((s < 31) ? (1 << s) : (Math.pow(2, s))); };
result.lshift = lshift;
// returns (a + b) % c, taking overflow into account (in JS, overflow means reaching a part in the floating point representation where it can no longer distinguish 1)
var modadd = supportbigint ?
function(a, b, c) { return mod(a + b, c); } :
function(a, b, c) {
if (a + b < 9007199254740992) return mod(a + b, c);
if(a + b > c) {
return mod(a - c + b, c);
}
// This assumes that c < 4503599627370496 or a + b doesn't overflow
return mod(mod(a, c) + mod(b, c), c);
};
// returns (a * b) % c, taking overflow into account
var modmul = supportbigint ?
function(a, b, c) { return mod(a * b, c); } :
function(a, b, c) {
if(a * b < 9007199254740992) return mod(a * b, c);
var x = 0;
var y = mod(a, c);
while(b > 0) {
if(b & 1) x = modadd(x, y, c);
y = modadd(y, y, c);
b = rshift1(b);
}
return x % c;
};
// Computes integer power (a**b) modulo m.
// Handles error cases as follows:
// Returns 0 if the output would be infinity (instead of throwing error) which happens if b < 0 and a == 0.
// Returns 0 if m is <= 0
// Returns 1 for the case of 0**0.
var modpow = function(a, b, m) {
if(m == 1) return n0; // anything modulo 1 is 0.
if(m <= 0) return n0; // error
// integer power
if(b < 0) {
if(a == 0) {
return n0; // actually infinity, but user must handle this as error case outside if desired
} else if(a == 1) {
return n1;
} else if(a == -1) {
return (b & n1) ? -n1 : n1;
} else {
return n0; // integer power result: truncation of the small value is 0.
}
} else if(b == 0) {
return n1;
} else {
var neg = a < 0;
if(neg) a = -a;
var r = n1;
var pot = ((m & (m - n1)) == 0); // power of two, so can use faster mask instead of modulo division
if(pot) {
var mask = m - n1;
a &= mask;
while(b > 0) {
if(b & n1) r = ((r * a) & mask);
b = rshift1(b);
a = ((a * a) & mask);
}
} else {
r = n1;
a %= m;
while(b > 0) {
if(b & n1) r = modmul(r, a, m);
b = rshift1(b);
a = modmul(a, a, m);
}
}
if(neg && (b & n1)) {
r = -r;
}
return r;
}
};
result.modpow = modpow;
// returns floored integer log b of a (e.g. b = 2 gives log2)
// that is, returns largest integer k such that b**k <= a
// error cases: returns 0 if a <= 0 or b <= 1
var intlog = function(a, b) {
if(b <= 1) return n0;
if(a <= 1) return n0;
if(a == b) return n1;
var r = n0;
while(a > 0) {
r++;
a = intdiv(a, b);
}
return r - n1;
};
result.intlog = intlog;
// computes floored integer root b of a (e.g. b = 2 gives sqrt, b=3 gives cbrt)
// that is, computes largest integer k such that k**b <= a
// b must be positive integer
// returns array with [result, boolean error]
var introot = function(a, b) {
if(b <= 0) return [n0, true];
if(b == 1) return [a, false];
var neg = a < 0;
if(neg && !(b & n1)) return [n0, true];
if(neg) a = -a;
//if n is bigger than log2(a), the result is smaller than 2
var l = log2(a);
if(l == 0) return [n0, true];
if(b > l) return [neg ? -n1 : n1, false];
var low = n0;
// high must be higher than the solution (not equal), otherwise the comparisons below don't work correctly.
// estimate for higher bound: exact non-integer solution of a ^ (1 / b) is 2 ** (log2(a) / b)
// integer approximation: ensure to use ceil of log2(a)/b to have higher upper bound, and add 1 to be sure it's higher.
// ceil of log2(a) is l + 1, and ceil of (l + 1) / b is intdiv(l + b + 1 - 1, b)
var high = (n2 ** intdiv(l + b, b)) + n1;
var r;
for (;;) {
var r = (low + high) >> n1;
var rr = r ** b;
if(rr == a) return [neg ? -r : r, false];
else if(rr < a) low = r;
else high = r;
if(high <= low + n1) {
return [neg ? -low : low, false];
}
}
};
result.introot = introot;
// integer modular inverse 1 / a modulo b
// error cases: if a is 0 or m <= 0, returns 0
var modinv = function(a, b) {
if(a == 0 || m == 0) {
return n0;
} else {
a = mod(a, b);
var r = n0;
var b0 = b;
var x = n1, y = n0;
for(;;) {
if(a == 1) { r = x; break; }
if(a == 0) { r = n0; break; }
var d = intdiv(b, a);
var m = b - d * a; // modulo (matching floored division)
y -= x * d;
b = m;
if(b == 1) { r = y; break; }
if(b == 0) { r = n0; break; }
d = intdiv(a, b);
m = a - d * b; // modulo (matching floored division)
x -= y * d;
a = m;
}
if(r < 0) r += b0;
return r;
}
};
result.modinv = modinv;
// integer log2
// error cases: returns 0 if a <= 0
var log2 = function(a) {
if(a <= 1) return n0;
var r = n0;
while(a > 0) {
r++;
a >>= n1;
}
return r - n1;
};
result.log2 = log2;
// integer sqrt
// error cases: returns 0 if a < 0
var sqrt = function(a) {
if(a <= 0) return n0;
var r = n0;
var s = n2;
var as = a >> s;
while(as != 0) {
s += n2;
as = a >> s;
}
while(s >= 0) {
r <<= n1;
var c2 = r + n1;
if(c2 * c2 <= (a >> s)) {
r = c2;
}
s -= n2;
}
return r;
};
result.sqrt = sqrt;
// factorial of a modulo b. returns array of [result, overflow]
// overflow means the real (non-modulo) result is larger than b, or error condition
// error cases:
// - returns 0 and sets overflow if a < 0
// - returns 0 and sets overflow if b <= 0
// if opt_nooverflow is true, will not treat output larger than b as overflow (but still use the overflow flag for error conditions)
// NOTE: can be slow for a > 4096 especially if b only has large prime factors
var factorial = function(a, b, opt_nooverflow) {
if(a < 0) return [n0, true];
if(b <= 0) return [n0, true];
var pot = ((b & (b - n1)) == 0); // power of two, so can use faster mask instead of modulo division
// if a/2 is larger than amount of output bits,
// then we know that all visible output bits will be 0, due to the amount of
// factors '2' in the result. So no need to compute then, plus also
// indicate overflow
if(pot && a > log2(b) * n2) return [n0, true && !opt_nooverflow];
// if a is larger than b, then it's guaranteed that the modulo value itself
// is a factor and we know the output modulo b will be 0.
if(a >= b) return [n0, true && !opt_nooverflow];
var r = n1;
var overflow = false;
if(pot) {
var mask = b - n1;
for(var i = n2; i <= a; i++) {
r *= i;
if(r > mask) {
if(!opt_nooverflow) overflow = true;
r &= mask;
if(r == 0) break;
}
}
} else {
if(a >= b) {
// result is guaranteed to be 0, since the modulo itself will be
// contained in the factors when a >= b. So no need to compute.
r = n0;
} else {
for(var i = n2; i <= a; i++) {
r *= i;
if(r > b) {
if(!opt_nooverflow) overflow = true;
r = mod(r, b);
// once the modulo operation made the result 0, which can easily happen as soon
// as we passed all the prime factors of b, we can stop since the result is
// guaranteed to stay 0.
if(r == 0) break;
}
}
}
}
return [r, overflow];
};
result.factorial = factorial;
// return array of [isprime, error]
var isprime = function(n) {
if(n < 2) return [false, false];
if((n & n1) == 0) return [(n == 2) ? true : false, false];
if((n % n3) == 0) return [(n == 3) ? true : false, false];
if((n % n5) == 0) return [(n == 5) ? true : false, false];
if((n % n7) == 0) return [(n == 7) ? true : false, false];
if(!supportbigint && n > 9007199254740991) return [false, true];
if(supportbigint && n.toString(16).length > 180) return [false, true]; // too slow for running inside LogicEmu components
if(n < 1500000) {
if(supportbigint) n = Number(n); // no need for BigInt for this part
var s = Math.ceil(Math.sqrt(n)) + 6;
p = Math.floor(7 / 6) * 6;
while(p < s) {
if(n % (p - 1) == 0 || n % (p + 1) == 0) return [false, false];
p += 6;
}
return [true, false];
} else {
// Miller-Rabin
var base;
if(n < 1373653) base = [2, 3];
else if(n < 9080191) base = [31, 73];
else if(n < 4759123141) base = [2, 7, 61];
else if(n < 1122004669633) base = [2, 13, 23, 1662803];
else if(n < 2152302898747) base = [2, 3, 5, 7, 11];
else if(n < 3474749660383) base = [2, 3, 5, 7, 11, 13];
else if(n < 341550071728321) base = [2, 3, 5, 7, 11, 13, 17];
else if(n < 3770579582154547) base = [2, 2570940, 880937, 610386380, 4130785767];
else base = [2, 325, 9375, 28178, 450775, 9780504, 1795265022]; //valid up to >2^64
for(var i = 0; i < base.length; i++) base[i] = B(base[i]);
var d = rshift1(n);
var s = n1;
while(!(d & n1)) {
d = rshift1(d);
++s;
}
var witness = function(n, s, d, a) {
var x = modpow(a, d, n);
var y;
while(s) {
y = modmul(x, x, n);
if(y == n1 && x != n1 && x != n - n1) return [false, false];
x = y;
s--;
}
return y == 1;
};
for(var i = 0; i < base.length; i++) {
if(!witness(n, s, d, base[i])) return [false, false];
}
return [true, false];
}
};
result.isprime = isprime;
// returns smallest prime that is >= n
// returns -1 if error
var nextprime = function(n) {
if(n <= 2) return n2;
if(n <= 3) return n3;
if(!supportbigint && n >= 9007199254740881) return -n1;
if(supportbigint && n.toString(16).length > 180) return -n1; // too slow for running inside LogicEmu components
if(isprime(n)[0]) return n;
var m = n % n6;
var step = n2;
if(m == 0 || m == 5) {
n += (m == 0 ? n1 : n2);
step = n4;
} else {
n += (n5 - m);
}
for(;;) {
var p = isprime(n);
if(p[1]) return -n1; // error
if(p[0]) return n;
n += step;
step ^= n6; //swap step between 2 and 4
}
};
result.nextprime = nextprime;
// returns largest prime that is <= n
// returns -1 if error
var prevprime = function(n) {
if(n < 2) return -n1; // there is no lower prime
if(n < 3) return n2;
if(n < 5) return n3;
if(n < 7) return n5;
if(!supportbigint && n > 9007199254740881) return -n1; // not supported if no BigInt
if(supportbigint && n.toString(16).length > 180) return -n1; // too slow for running inside LogicEmu components
if(isprime(n)[0]) return n;
var m = n % n6;
var step = n2;
if(m == 0 || m == 1) {
n -= (m + n1);
step = n4;
} else {
n -= (m - n1);
}
for(;;) {
var p = isprime(n);
if(p[1]) return -n1; // error
if(p[0]) return n;
n -= step;
step ^= n6; //swap step between 2 and 4
}
};
result.prevprime = prevprime;
// returns the highest possible exponent if the number is a perfect power (>= 2), or 1 if not.
// e.g. if n is 8, returns 3 because 2^3 is 8, if n is 10 returns 1.