-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathengine_dev.js
1824 lines (1687 loc) · 69.9 KB
/
engine_dev.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
// Calchemy (tm); Math Magic; http://www.calchemy.com
// Copyright (c) 1988-2023 Ken Burgess and Rich Testardi.
// This is the calchemy engine; it loads the database one line at a time and then runs user command lines one at a time, returning their output.
// regular expressions for string identification
// XXX -- token can use typeof for value; something for function call; anything for operator?
const value_regexp_ch = /[0-9.]/;
const value_regexp = /[0-9]*\.?[0-9]*([eE][-+]?[0-9]+)?/;
const value_regexp_head = /^[0-9]*\.?[0-9]*([eE][-+]?[0-9]+)?/;
const value_regexp_tail = /[0-9]*\.?[0-9]*([eE][-+]?[0-9]+)?$/;
const value_regexp_cap = /[(]([0-9]*\.?[0-9]*([eE][-+]?[0-9]+)?)[)][^^ ]/g;
const unit_regexp_ch = /[_A-Za-z$%]/;
const unit_regexp = /[_A-Za-z$%][_A-Za-z0-9$%]*/;
const unit_regexp_head = /^[_A-Za-z$%][_A-Za-z0-9$%]*/;
const unit_regexp_tail = /[_A-Za-z$%][_A-Za-z0-9$%]*$/;
const xunit_regexp_head = /^[:_A-Za-z$%][_A-Za-z0-9$%:]*/;
const xunit_regexp_tail = /[:_A-Za-z$%][_A-Za-z0-9$%:]*$/;
const unit_regexp_all = /^[_A-Za-z$%][_A-Za-z0-9$%]*$/;
const unit_regexp_cap = /[(]([_A-Za-z$%][_A-Za-z0-9$%]*)[)][^^ ]/g;
const operator_regexp_ch = /[-+*/^;?()\[\]{},:=~|]/;
const opens = "([{";
const closes = ")]}";
const semicolon_alternates = "@&#!"; // prefix alternate = ~
const functions = { "square":1, "cubic":1, "sqrt":1, "sin":1, "cos":1, "tan":1, "asn":1, "acs":1, "atn":1, "ln":1, "log":1, "exp":1, "per":1 };
// this is our units database
var nextbaseunit = 0;
var freebaseunit = 0;
var units = []; // Unit
var bases = []; // Unit
var all_categories = []; // string
var open_categories = []; // string
var loading = false; // while loading the units database, all ambiguities are turned off and primary names must be used
var deriving = false; // while deriving units, secondary names may also be used
var defining = false; // while defining, don't record mismatches
var evaluating = false; // while evaluating units, free units may be used
var testing = false; // while testing, don't prompt for equation values
var storagebase; // may be undefined
var database_tests = "";
var invert_warn = false; // auto-invert left-hand-side
var offset_warn = false; // degC, absC, degF, absF
var offset_warned = false;
var cycle_warn = false; // category Angle
var cycle_warned = false;
// these are the results from a command line
var results; // Unit
var mismatches; // string
var errors; // string
var defines; // boolean
var undefines; // boolean
function assert(bool)
{
if (! bool) {
throw "assertion failed";
}
}
// return the index of the matching parenthesis in an array of tokens
function MatchParen(tokens, i)
{
var stack = [];
var k = opens.indexOf(tokens[i]);
assert(k != -1);
stack.push(k);
for (var j = i+1; j < tokens.length; j++) {
k = opens.indexOf(tokens[j]);
if (k != -1) {
stack.push(k);
} else if (tokens[j] == closes[stack[stack.length-1]]) {
stack.pop();
if (! stack.length) {
return j;
}
}
}
throw "unmatched parenthesis " + opens[stack[stack.length-1]];
}
// add parenthesis around an interpretation if they are not already there
function Parenthesize(interpretation)
{
if (interpretation[0] == '(' && MatchParen(interpretation, 0) == interpretation.length-1) {
return interpretation;
}
return "(" + interpretation + ")";
}
// *** unit functions *****************************************************************************
class Unit {
// return an empty or initialized unit
constructor(names, pluralizables, coefficient, exponents, type, prefixable, categories, definition)
{
this.names = (names == undefined) ? [] : names.slice(0); // array of unit names
this.pluralizables = (pluralizables == undefined) ? [] : pluralizables.slice(0); // array of booleans
this.coefficient = (coefficient == undefined) ? NaN : coefficient; // floating point
this.exponents = (exponents == undefined) ? [] : exponents; // array of integers
this.type = (type == undefined) ? null : type; // null || "BASE" || "DERIVED" || "PREFIX" || "VALUE"
this.prefixable = (prefixable == undefined) ? false : prefixable; // boolean
this.categories = (categories == undefined) ? [] : categories; // array of unit category names
this.definition = (definition == undefined) ? "" : definition; // string
this.interpretation = (names == undefined) ? "" : names[0]; // string
this.dimension = ""; // string, only for SI results
}
// pi analysis; check if orders of PI and RADIAN are within limits
PiAnalysis()
{
// if exponents are beyond PI and RADIAN...
if (this.exponents.length > 1) {
if (this.exponents[0] && this.exponents[1]) {
return false;
}
}
return true;
}
// test if scalar zero
Zero()
{
if (this.coefficient) {
return false;
}
for (var i = 0; i < this.exponents.length; i++) {
if (this.exponents[i]) {
return false;
}
}
return true;
}
// test if dimensions are compatible
Compatible(unit, invert)
{
if (! unit) {
return true;
}
// dynamically expand exponents arrays as needed
var maxbaseunits = Math.max(this.exponents.length, unit.exponents.length);
for (var i = this.exponents.length; i < maxbaseunits; i++) {
this.exponents[i] = 0;
}
for (i = unit.exponents.length; i < maxbaseunits; i++) {
unit.exponents[i] = 0;
}
// for all exponents beyond PI and RADIAN...
for (i = 2; i < this.exponents.length; i++) {
// if the exponent does not match...
if (this.exponents[i] != (invert?-1:1)*unit.exponents[i]) {
// units are incompatible
return false;
}
}
// units are compatible
return true;
}
// test if units are equal (so we can undefine specifically)
Equal(unit)
{
return this.Compatible(unit, false) && this.coefficient == unit.coefficient;
}
// test if unit is ambiguous with others (so we don't define one ambiguously unintentionally)
Ambiguous()
{
for (var i = 0; i < units.length; i++) {
if (units[i].type == "DERIVED") {
if (this.Compatible(units[i], false)) {
return units[i];
}
}
}
return null;
}
// perform an operation on a unit and return the resulting result
Operate(op, rhs, derivedok)
{
var unit = new Unit();
// dynamically expand exponents arrays as needed
var maxbaseunits = Math.max(this.exponents.length, rhs.exponents.length);
for (var i = this.exponents.length; i < maxbaseunits; i++) {
this.exponents[i] = 0;
}
for (i = rhs.exponents.length; i < maxbaseunits; i++) {
rhs.exponents[i] = 0;
}
if (! testing && derivedok != true) {
// XXX -- can we get rid of this code path difference for testing???
if (this.type == "DERIVED") {
throw "specify value for " + this.names[0];
}
if (op != ':' && op != "pow" && op != '^' && rhs.type == "DERIVED") {
throw "specify value for " + rhs.names[0];
}
}
var offset = 0;
if (this.type == "VALUE" && op == ' ') {
if (rhs.names[0] == "absC" || rhs.names[0] == "degC") {
offset = 273.15;
offset_warn = true;
} else if (rhs.names[0] == "absF" || rhs.names[0] == "degF") {
offset = 459.67;
offset_warn = true;
}
} else if (op == '?') {
if (rhs.names[0] == "absC" || rhs.names[0] == "degC") {
offset = 273.15;
offset_warn = true;
} else if (rhs.names[0] == "absF" || rhs.names[0] == "degF") {
offset = 459.67;
offset_warn = true;
}
}
var invert = false;
if (op == '?' && ! this.Compatible(rhs, false) && this.Compatible(rhs, true)) {
// auto-invert left-hand-side
invert = true;
}
// if we are not loading the database...
if (! loading) {
var display = null;
var dividing = false;
var multiplying = false;
var adding = false;
switch (op) {
case '~':
display = "~";
multiplying = true;
break;
case '>':
display = '+';
adding = true;
break;
case '<':
display = '-';
adding = true;
break;
case "pow":
case '^':
display = '^';
break;
case ' ':
display = op;
multiplying = true;
break;
case '*':
display = ' ' + op + ' ';
multiplying = true;
break;
case "per":
case '/':
display = ' ' + op + ' ';
dividing = true;
break;
case '+':
case '-':
display = ' ' + op + ' ';
adding = true;
break;
case ':':
break;
case '@':
display = " * ";
multiplying = true;
break;
case '&':
display = " / ";
dividing = true;
break;
}
// format interpretations to display with results
if ((this.multiplying == true || rhs.multiplying == true) && (multiplying || dividing)) {
if (this.dividing) {
// add the deferred parenthesis for the lhs now, if it differs from the current operation
this.interpretation = Parenthesize(this.interpretation);
}
if ((rhs.multiplying && ! multiplying) || rhs.dividing) {
// add the deferred parenthesis for the rhs now, if it differs from the current operation
rhs.interpretation = Parenthesize(rhs.interpretation);
}
// continue multiplication or a single division without parenthesis; we'll add them later
assert(display != null);
unit.interpretation = this.interpretation + display + rhs.interpretation;
} else {
var interpretation;
if (op == '?') {
if (invert) {
// auto-invert left-hand-side
interpretation = Parenthesize(this.interpretation) + " ^ -1";
} else {
interpretation = this.interpretation;
}
// no need for deferred parenthesis at the outermost operation
if (offset) {
unit.interpretation = "(" + interpretation + " ? " + rhs.interpretation.replace(/(abs|deg)/, "delta") + ") - " + offset;
} else {
unit.interpretation = interpretation + " ? " + rhs.interpretation;
}
dividing = true;
} else if (op == ':') {
// dimensional filter
unit.interpretation = this.interpretation;
} else {
if (offset) {
interpretation = "(" + this.interpretation + " + " + offset + ")";
} else {
interpretation = this.interpretation;
}
if (this.multiplying || this.dividing || op == "pow" || op == '^') {
// add the deferred or required parenthesis for the lhs now
interpretation = Parenthesize(interpretation);
}
if (rhs.multiplying || rhs.dividing) {
// add the deferred parenthesis for the rhs now
rhs.interpretation = Parenthesize(rhs.interpretation);
}
if (display != null) {
// normal infix operations
if (offset) {
unit.interpretation = interpretation + display + rhs.interpretation.replace(/(abs|deg)/, "delta");
} else {
unit.interpretation = interpretation + display + rhs.interpretation;
}
if (adding) {
// add required parenthesis now
unit.interpretation = Parenthesize(unit.interpretation);
}
} else if (op == '#') {
// solve by dimensional analysis: r/l
unit.interpretation = Parenthesize(interpretation) + "^-1 * " + rhs.interpretation;
} else if (op == '!') {
// solve by dimensional analysis: 1/(lr)
unit.interpretation = Parenthesize(interpretation + " * " + rhs.interpretation) + "^-1";
} else {
assert(0);
}
}
}
// remove degenerate parenthesis
var orig;
do {
orig = unit.interpretation;
unit.interpretation = unit.interpretation.replace(unit_regexp_cap, "$1").replace(value_regexp_cap, "$1");
} while (orig != unit.interpretation);
// propagate the need for deferred parenthesis
assert(! (multiplying && dividing));
unit.multiplying = multiplying;
unit.dividing = dividing;
}
switch (op) {
case "pow":
case '^':
// raise coefficient to dimensionless power; multiply exponents by power
unit.coefficient = Math.pow(this.coefficient, rhs.coefficient);
for (i = 0; i < maxbaseunits; i++) {
if (rhs.exponents[i]) {
throw "non-dimensionless exponent";
}
unit.exponents[i] = (this.exponents[i] * rhs.coefficient).toPrecision(4) * 1; // N.B. * 1 returns to float
// check for non-integral exponents beyond PI and RADIAN
if (i > 1 && unit.exponents[i] != Math.round(unit.exponents[i])) {
throw "non-integral exponent";
}
}
break;
case '~': // prefix
case ' ': // implicit
case '*':
case '@': // solve by dimensional analysis: l*r
// multiply coefficients; add exponents
// if this is an offset temperature being entered, instantly convert from offset temperature to absolute temperature
unit.coefficient = (this.coefficient + offset) * rhs.coefficient;
for (i = 0; i < maxbaseunits; i++) {
unit.exponents[i] = this.exponents[i] + rhs.exponents[i];
}
break;
case "per": // unit division
case '/':
case '&': // solve by dimensional analysis: l/r
case '?':
// divide coefficients; subtract exponents
// if this is an offset temperature being computed, instantly convert from absolute temperature back to offset temperature
if (invert) {
unit.coefficient = (1 / this.coefficient / rhs.coefficient) - offset;
} else {
unit.coefficient = (this.coefficient / rhs.coefficient) - offset;
}
for (i = 0; i < maxbaseunits; i++) {
if (invert) {
unit.exponents[i] = - this.exponents[i] - rhs.exponents[i];
} else {
unit.exponents[i] = this.exponents[i] - rhs.exponents[i];
}
}
break;
case '#': // solve by dimensional analysis: r/l
// divide coefficients; subtract exponents
unit.coefficient = rhs.coefficient / this.coefficient;
for (i = 0; i < maxbaseunits; i++) {
unit.exponents[i] = rhs.exponents[i] - this.exponents[i];
}
break;
case '!': // solve by dimensional analysis: 1/(lr)
// divide coefficients; subtract exponents
unit.coefficient = 1 / (this.coefficient * rhs.coefficient);
for (i = 0; i < maxbaseunits; i++) {
unit.exponents[i] = - this.exponents[i] - rhs.exponents[i];
}
break;
case '>': // unary
case '+':
// add coefficients for compatible exponents
if (! this.Zero() && ! this.Compatible(rhs, false)) {
throw "addition of dissimilar units";
}
unit.coefficient = this.coefficient + rhs.coefficient;
unit.exponents = rhs.exponents;
if (op == '>') {
unit.type = rhs.type; // preserve for unary
}
break;
case '<': // unary
case '-':
// subtract coefficients for compatible exponents
if (! this.Zero() && ! this.Compatible(rhs, false)) {
throw "subtraction of dissimilar units";
}
unit.coefficient = this.coefficient - rhs.coefficient;
unit.exponents = rhs.exponents;
if (op == '<') {
unit.type = rhs.type; // preserve for unary
}
break;
case ':':
// filter out different dimensions
if (! this.Compatible(rhs, false)) {
if (this.type == "BASE") {
throw "specify value for " + this.names[0]; //OK
} else {
throw "incompatible units :" + rhs.interpretation; //OK
}
}
unit.coefficient = this.coefficient;
unit.exponents = this.exponents;
break;
default:
throw "unknown operator " + op;
//break;
}
return unit;
}
// format a unit as a dimension string
Dimension(question)
{
var strings = [];
// look for single dimension matches, possibly inverted
var i;
var j;
var cont;
var string = (question?"Dimensional Mismatch ":"") + "[";
// for uninverted and then inverted...
cont = false;
for (var invert = 0; invert < 2; invert++) {
// report ^-1 if the number of inversions is odd
var xor = Boolean(question)!=Boolean(invert);
// for all units...
for (i = 0; i < units.length; i++) {
// if this unit is a dimension...
if (units[i].type == "DERIVED") {
// if this unit is a compatible dimension...
if (this.Compatible(units[i], xor)) {
// format its name
if (cont) {
// "or" if more than one
string += " or ";
}
string += units[i].names[0] + (invert?"^-1":"");
cont = true;
}
}
}
}
// count the number of non-0 dimensions
j = 0;
for (i = 2; i < nextbaseunit; i++) {
if (this.exponents[i]) {
j += Math.abs(this.exponents[i]);
}
}
// if we don't have a matching derived dimension or there is more than one non-0 dimension...
if (! cont || j > 1) {
// also match individual base dimensions and powers
if (cont) {
// "or" if more than one
string += " or ";
}
// for each base unit beyond PI and RADIAN...
cont = false;
for (i = 2; i < nextbaseunit; i++) {
// if the exponent is non-0...
var remaining = this.exponents[i]*(question?-1:1);
if (remaining) {
// format its name
if (cont) {
// multiply if more than one
string += "*";
}
string += bases[i].names[0] + (remaining!=1?"^"+remaining:"");
cont = true;
}
}
}
string += "]";
// return the individual base dimensions and powers
strings.push("> " + Simplify(this.interpretation));
strings.push(string);
return strings;
}
// format a unit as an SI result string
SI()
{
// look for a single dimension match, possibly inverted
var i;
var denom;
var result;
var results = [];
// for uninverted and then inverted...
for (var invert = 0; invert < 2; invert++) {
// for all units...
for (i = 0; i < units.length; i++) {
// if this unit is a derived unit...
if (units[i].type == "DERIVED") {
// if this unit is a compatible derived unit...
if (this.Compatible(units[i], invert)) {
// calculate the SI result in terms of the derived unit
denom = units[i].Operate('^', Value(invert?-1:1), true);
denom.interpretation = "[" + units[i].names[0] + "]" + (invert?"^-1":"");
result = this.Operate('?', denom, true);
result.dimension = (invert?"(":"") + units[i].definition.replace(/.*= */, "").replace(/ *[#].*/, "").trim() + (invert?")^-1":"");
if (result.PiAnalysis()) {
// we have a winner
results.push(result);
if (units[i].categories.includes("Warn_angle")) {
cycle_warn = true;
}
}
}
}
}
// if we found a result...
if (results.length) {
// N.B. if we match an uninverted dimension, skip the inverted ones
// return it
return results;
}
}
// otherwise, we have to match individual base dimensions and powers
denom = null;
var string = "";
// for each exponent beyond PI and RADIAN...
for (i = 2; i < this.exponents.length; i++) {
// if the exponent is non-0...
if (this.exponents[i]) {
// find the derived unit for the exponent
var exponent = this.exponents[i];
for (var ii = 0; ii < units.length; ii++) {
if (units[ii].type == "DERIVED" && bases[i].Compatible(units[ii], false)) {
// and divide the overall result by the derived unit
var term;
if (exponent == 1) {
term = units[ii];
} else {
term = units[ii].Operate('^', Value(this.exponents[i]), true);
}
if (! denom) {
denom = term;
} else {
// multiply if more than one term
denom = denom.Operate('*', term, true);
string += "*";
}
// format the derived unit name
string += units[ii].definition.replace(/.*= */, "") + (exponent!=1?"^"+exponent:"");
break;
}
}
// if we did not find a derived unit...
if (ii == units.length) {
throw "missing DERIVED unit for " + bases[i].names[0];
}
}
}
// return the overall coefficient and individual base dimensions and powers
if (! denom) {
denom = Value(1).Operate('^', Value(1), true);
}
denom.interpretation = "";
result = this.Operate('?', denom, true);
result.dimension = string;
results.push(result);
return results;
}
}
// define a new base unit in the units database
function DefineBaseUnit(names, pluralizable)
{
// pick a new exponent
var unit = new Unit(names, [pluralizable], 1, [], "BASE", false, [], "");
for (var i = 0; i < nextbaseunit; i++) {
unit.exponents[i] = 0;
}
// set just this exponent to 1
unit.exponents[nextbaseunit] = 1;
bases[nextbaseunit] = unit;
nextbaseunit++;
// make the unit (mostly) immutable
Object.freeze(unit);
units.push(unit);
// return the unit
return unit;
}
// return a primary unit from the units database
// N.B. caller must throw!
function LookupUnit(name)
{
// if this is a precomputed unit to make loading faster
if (name[0] == 'x' && name.match(/^xx[0-9]/)) {
// no need to search, just return the unit
return units[name.replace(/^xx/, "")];
}
// otherwise, for all units...
for (var i = 0; i < units.length; i++) {
var unit = units[i];
// for all appropriate unit names...
for (var j = 0; j < unit.names.length; j++) {
// if the name matches...
if (name == unit.names[j]) {
// return the unit
return unit;
}
if (loading && ! deriving) {
// be quick
break;
}
if (unit.type == "PREFIX") {
break;
}
}
}
// unit not found
return null;
}
// return a prefix and a primary unit from the units database
function LookupPrefixedUnit(name)
{
// for all unit names...
for (var ii = 0; ii < units.length; ii++) {
// if this is a prefix...
if (units[ii].type == "PREFIX") {
var storage = units[ii].names[0].slice(2) == "bi"; // storage prefix
// for all prefix names...
for (var jj = 0; jj < units[ii].names.length; jj++) {
var prefix = units[ii].names[jj];
// if the specified name matches the prefix...
if (name[0] == prefix[0] && name.indexOf(prefix) == 0 && name.length > prefix.length) {
// prefix match
var remain = name.slice(prefix.length);
// for all unit names...
for (var i = 0; i < units.length; i++) {
// if this unit is prefixable...
if (units[i].prefixable) {
if (storage && (units[i].exponents.length < storagebase || units[i].exponents[storagebase] == 0)) {
// not storage
continue;
}
// for all unit names...
for (var j = 0; j < units[i].names.length; j++) {
// if the remainder of the specified name matches the unit...
if (remain == units[i].names[j]) {
// return the prefix and unit
return [units[ii], units[i]];
}
if (loading && ! deriving) {
// be quick
break;
}
}
}
}
}
if (loading && ! deriving) {
// be quick
break;
}
}
}
}
// prefix and unit not found
throw "undefined unit " + name;
}
// *** expression evaluation **********************************************************************
// return a literal value as a unit
function Value(token)
{
var unit = new Unit([token]);
unit.coefficient = Number(token);
if (isNaN(unit.coefficient)) {
throw "bad value " + token; //OK
}
unit.type = "VALUE";
return unit;
}
// operator precedences
var prec = {
'~': 3, // left-to-right associativity (prefix multiplication)
'>': 2, // right-to-left associativity (unary +)
'<': 2, // right-to-left associativity (unary -)
"pow": 1, // left-to-right associativity (square, cube, sqrt)
'^': 1, // right-to-left associativity
' ': 0, // left-to-right associativity (implied multiplication)
"per": -1, // left-to-right associativity (unit division)
'*': -1, // left-to-right associativity
'/': -1, // left-to-right associativity
'+': -2, // left-to-right associativity
'-': -2, // left-to-right associativity
':': -3, // left-to-right associativity (dimensional filter)
'@': -4, // left-to-right associativity (solve by dimensional analysis: l*r)
'&': -4, // left-to-right associativity (solve by dimensional analysis: l/r)
'#': -4, // left-to-right associativity (solve by dimensional analysis: r/l)
'!': -4, // left-to-right associativity (solve by dimensional analysis: 1/(lr))
'?': -5, // left-to-right associativity
"zz": -7,
};
// operator associativities
var right = "<>^";
// clean low precedence operators off the stack and push a new operator on the stack if needed and set the next result
function CleanAndPush(stack, result, op, next)
{
assert(prec.hasOwnProperty(op));
// handle stacked operator precedence and associativity; clean stack as needed
if (result != null || op == 'zz') {
while (stack.length) {
// get the top operation on the stack
var stacked = stack[stack.length-1];
// if the operator has right-to-left associativity, pop if the operator precedence is greater-than the current precedence;
// otherwise, pop if the operator precedence is greater-than-or-equal-to the current precedence
var pop = (right.indexOf(stacked.op) != -1) ? (stacked.prec > prec[op]) : (stacked.prec >= prec[op]);
if (! pop) {
// we're done popping
break;
}
// pop and clean
stacked = stack.pop();
if (result != null) {
// perform the stacked operation
result = stacked.result.Operate(stacked.op, result);
} else {
// SI result requested thru '?' with no rhs; no operation
assert(stacked.op == '?');
result = stacked.result;
}
}
}
// if we are still evaluating (and not finalizing the stack)...
if (op != "zz") {
// if there is a previous result...
if (result != null) {
// push the previous result and a new operator on the stack
stack.push({ result: result, op: op, prec: prec[op] });
}
// and set the current result
result = next;
}
// return the current result
return result;
}
// evaluate a single expression in an array of tokens and return a single result
function EvaluateTokens(tokens)
{
var j;
var subtokens;
var stack = [];
var token = null;
var result = null;
// for all tokens in the equation...
for (var i = 0; i < tokens.length; i++) {
token = tokens[i];
// if the token is a function call...
if (functions.hasOwnProperty(token)) {
if (token == "per") {
// unit division
result = CleanAndPush(stack, result, token, null);
} else {
var unit;
if (tokens.length > i+1 && opens.indexOf(tokens[i+1]) != -1) {
// power, trig, log, etc. followed by parenthetical expression
j = MatchParen(tokens, i+1);
subtokens = tokens.slice(i+2, j);
unit = EvaluateTokens(subtokens);
i = j;
} else if (tokens.length > i+3 && tokens[i+2] == '~') {
// power, trig, log, etc. followed by prefixed unit
unit = EvaluateTokens([tokens[i+1], '~', tokens[i+3]]);
i = i+3;
} else if (tokens.length > i+1) {
// power, trig, log, etc. followed by unit or number
unit = EvaluateTokens([tokens[i+1]]);
i = i+1;
} else {
throw "missing argument " + tokens[i];
}
result = CleanAndPush(stack, result, ' ', unit);
if (token == "square") {
result = CleanAndPush(stack, result, "pow", Value("2"));
} else if (token == "cubic") {
result = CleanAndPush(stack, result, "pow", Value("3"));
} else if (token == "sqrt") {
result = CleanAndPush(stack, result, "pow", Value("0.5"));
} else {
var interpretation = token + "{" + result.interpretation + "}";
// check that argument is dimensionless beyond PI and RADIAN...
for (j = 2; j < result.exponents.length; j++) {
if (result.exponents[j]) {
throw "non-dimensionless argument"; //OK
}
}
if (token == "sin") {
result = Value(Math.sin(result.coefficient));
} else if (token == "cos") {
result = Value(Math.cos(result.coefficient));
} else if (token == "tan") {
result = Value(Math.tan(result.coefficient));
} else if (token == "asn") {
// range -1..1
result = Value(Math.asin(result.coefficient));
} else if (token == "acs") {
// range -1..1
result = Value(Math.acos(result.coefficient));
} else if (token == "atn") {
result = Value(Math.atan(result.coefficient));
} else if (token == "ln") {
result = Value(Math.log(result.coefficient));
} else if (token == "log") {
result = Value(Math.log(result.coefficient)/Math.log(10));
} else if (token == "exp") {
result = Value(Math.exp(result.coefficient));
} else {
throw "bad function " + token;
}
result.interpretation = interpretation;
}
}
// otherwise, if the token opens a parenthetical expression...
} else if (opens.indexOf(token) != -1) {
// parenthetical expression
j = MatchParen(tokens, i);
subtokens = tokens.slice(i+1, j);
result = CleanAndPush(stack, result, ' ', EvaluateTokens(subtokens));
i = j;
// otherwise, if the token is a numeric value...
} else if (token[0].match(value_regexp_ch)) {
// value
result = CleanAndPush(stack, result, ' ', Value(token));
// otherwise, if the token is a symbolic unit value...
} else if (token[0].match(unit_regexp_ch)) {
// look for an unprefixed unit
var next = LookupUnit(token);
var op = ' ';
// if not found...
if (! next) {
// look for a prefixed unit
var prefixunit = LookupPrefixedUnit(token);
next = prefixunit[0];
op = '~';
result = CleanAndPush(stack, result, op, next);
next = prefixunit[1];
}
if (next.categories.includes("Warn_angle")) {
cycle_warn = true;
}
result = CleanAndPush(stack, result, op, next);
// otherwise, if the token is an arithmetic operator...
} else if (prec.hasOwnProperty(token)) {
// operator
if (result == null) {
if (token == '+') {
// unary +
result = Value("0");
token = '>';
} else if (token == '-') {
// unary -
result = Value("0");
token = '<';
} else {
throw "expected a value before " + token;
}
}
result = CleanAndPush(stack, result, token, null);
} else {
throw "bad token " + token;
}
}
if (result == null && token != '?') {
throw "missing expression";
}
// finalize the stack, popping all remaining operations
result = CleanAndPush(stack, result, "zz", null);
assert(! stack.length);
return result;
}
// simplify an equation interpretation
function Simplify(interpretation)
{
// XXX -- alternate parens; remove redundant parens
if (interpretation[0] == '(' && MatchParen(interpretation, 0) == interpretation.length-1) {
interpretation = interpretation.slice(1, interpretation.length-1);
}
return interpretation.replace(/[{]/g, "(").replace(/[}]/g, ")");
}
// *** expression alternation *********************************************************************
// expand a free unit to singular form(s)
function Singulars(name)
{
var names = [name];
if (name.match(/..s$/)) {
if (name.match(/.ves$/)) {
names.push(name.replace(/ves$/, "f"));
names.push(name.replace(/ves$/, "fe"));
} else if (name.match(/.ies$/)) {
names.push(name.replace(/ies$/, "y"));
} else if (name.match(/.(s|sh|ch|x|z)es$/)) {
names.push(name.replace(/es$/, ""));
} else {
names.push(name.replace(/s$/, ""));
}