-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmath.js
2536 lines (2052 loc) · 75.4 KB
/
math.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
// math.js is the bot's math module
var Canvas = require('canvas');
var mJS = require('mathjs');
var alG = require('algebrite');
var regression = require('regression');
var nerdamer = require('nerdamer/all');
var {ComputationError, TokenizationError, functions:f, parse, evaluate, evaluateInfo, angleMode, ofCircle, normalToSuper, superToNormal, superScripts:ss} = require('./parsers/calculate.js');
var {parse:inequality, betweenInequality:between, inequalityOverlap:overlap} = require('./parsers/inequality.js');
var generateStepString = function(steps, tabLevel = 1) {
var str = '--- In ' + steps.current + ' ---\n';
for (var i = 0; i < steps.length; ++i) {
if (i === 0) {
str += '\t'.repeat(tabLevel) + '--- In ' + steps[i].current + ' ---';
}
if (typeof steps[i] === 'object') {
if (steps[i].length === 0) {
str += '\n' + '\t'.repeat(tabLevel + 1) + '_no steps_';
} else {
str += '\n' + '\t'.repeat(tabLevel) + generateStepString(steps[i], tabLevel + 1);
}
} else {
str += '\n' + '\t'.repeat(tabLevel) + steps[i];
}
}
return str;
};
//mJS.simplify.rules = mJS.simplify.rules.concat(['0 * n -> 0', '1 * n -> n', 'n^1 -> n', 'n1 * c / n2 / n3 -> (n1 * c) / (n2 * n3)', 'n1 * n2 / n2 -> n1', 'n1 / n2 / n3 -> n1 / (n2 * n3)']);
/**
utilites
**/
// returns the prefix of a number, e.g. 1 = st, 2 = nd
var numSuffix = function(num) {
var string = num.toString();
var lastChar = string.charAt(string.length - 1);
var nextLastChar = string.charAt(string.length - 2);
if (lastChar === '1') {
if (string.length === 1) {
return 'st';
} else {
if (nextLastChar === '1') {
return 'th';
} else {
return 'st';
}
}
} else if (lastChar === '2') {
return 'nd';
} else if (lastChar === '3') {
return 'rd';
} else {
return 'th';
}
};
// converts a hex to rgb
var hexToRgb = function(hex) {
var parsed = parseInt(hex, 16);
var r = (parsed >> 16) & 255;
var g = (parsed >> 8) & 255;
var b = parsed & 255;
return [r, g, b];
};
// random rgb value
var randomRgb = function() {
var num = Math.round(0xffffff * Math.random());
var r = num >> 16;
var g = num >> 8 & 255;
var b = num & 255;
return [r, g, b];
};
// returns true if the majority of the numbers in the array approach zero
var zeroDiff = function(arr) {
var count = 0;
for (var i = 1; i < arr.length; ++i) {
if (f.abs(arr[i]) < f.abs(arr[i - 1])) {
++count;
}
}
return count >= f.round(arr.length / 2);
};
// returns true if every number in an array is less than a certain threshold
var lessThreshold = function(arr, threshold) {
return arr.every((num) => num < threshold);
};
// returns true if the numbers in the array keep getting larger and larger
var largerDiff = function(arr) {
for (var i = 1; i < arr.length; ++i) {
if (arr[i] < arr[i - 1]) {
return false;
}
}
return true;
};
// replace a section of a string with a new one
String.prototype.boundReplace = function(str, start, end) {
return this.substring(0, start) + str + this.substring(start + str.length, end);
};
// takes a string, an index to start at in the string, and heads out in both directions of the string to find the indexes of parsed expressions
// this is good for power detection (like in .calculate) or finding when a function ends
// continueLeft, continueRigiht = if these regexes do not match the next character, it will stop
var findExpressionLimitsHere = function(str, begin, continueLeft, continueRight, characters = '') {
var charactersToTrack = characters.split('');
var index = begin;
var leftIndex = index;
var rightIndex = index;
var trackInfo = {
characters: []
};
var parenIndex = 0; // must be 0 in order to break from 'paren' mode
while (leftIndex >= 0) {
--leftIndex;
var current = str.charAt(leftIndex);
var potentitalObj = {
character: current,
index: leftIndex,
heading: -1,
};
if (current === ')') {
++parenIndex;
} else if (current === '(' && parenIndex !== 0) {
--parenIndex;
} else if (parenIndex === 0 && !continueLeft.test(current)) {
++leftIndex;
parenIndex = 0;
break;
}
potentitalObj.parenIndex = parenIndex;
if (charactersToTrack.includes(current)) {
trackInfo.characters.push(potentitalObj);
}
}
if (rightIndex === index && str.charAt(index + 1) === '-') {
++rightIndex;
}
while (rightIndex <= str.length) {
++rightIndex;
var current = str.charAt(rightIndex);
var potentitalObj = {
character: current,
index: rightIndex,
heading: 1,
};
if (current === '(') {
++parenIndex;
} else if (current === ')' && parenIndex !== 0) {
--parenIndex;
} else if (parenIndex === 0 && !continueRight.test(current)) {
--rightIndex;
parenIndex = 0;
break;
}
potentitalObj.parenIndex = parenIndex;
if (charactersToTrack.includes(current)) {
trackInfo.characters.push(potentitalObj);
}
}
var result = [leftIndex, rightIndex];
result.trackInfo = trackInfo;
return result;
};
// convert a string using the same conversion algorithm as math.calc.ceval
var convertCeval = function(exp, mode, calcVars, customFunctions) {
exp = exp.split(' ').join('').toLowerCase();
exp = parse(exp).toString();
return exp;
};
// convert a string to one accepted by mathjs
var convertToMJSUsable = function(str) {
var result = str;
// temporarily replace to all caps to test for logs
result = result.replace(/\blog\(/g, 'LOG(');
while (/\bLOG\(/g.test(result)) {
var index = result.indexOf('LOG') + 2;
var limits = findExpressionLimitsHere(result, index, /[A-Za-z\d\.]/, /[A-Za-z\d\.]/, ',');
// check the object of the limits result; if there is a comma detected with parenIndex 1, that means that the user provided a base for log(), and this replacement should not take place
var noLogComma = limits.trackInfo.characters.every(function(obj) {
return obj.parenIndex !== 1;
});
// there was no base provided, so add the base ,10) to the end of log(
if (noLogComma) {
result = result.substring(0, index - 2) + 'log' + result.substring(index + 1, limits[1]) + ',10)' + result.substring(limits[1] + 1, result.length);
} else { // there is a base, do nothing
result = result.substring(0, index - 2) + 'log' + result.substring(index + 1, result.length);
}
}
result = result.replace(/\bln\(/g, 'log(');
return result;
};
// convert a string given by mathjs to a normal one
var convertToUsable = function(str) {
var result = str.split(' ').join('');
result = result.replace(/\blog\(/g, 'ln(');
// temporarily replace to all caps to test for logs
result = result.replace(/\bln\(/g, 'LN(');
while (/\bLN\(/g.test(result)) {
var index = result.indexOf('LN') + 1;
var limits = findExpressionLimitsHere(result, index, /[A-Za-z\d\.]/, /[A-Za-z\d\.]/, ',');
// check the object of the limits result; if there is a comma detected with parenIndex 1, that means that mathJS wrote log(x, with a base)
var noLogComma = limits.trackInfo.characters.every(function(obj) {
return obj.parenIndex !== 1;
});
// there was no base provided, so leave as is
if (noLogComma) {
result = result.substring(0, index - 1) + 'ln' + result.substring(index + 1, result.length);
} else { // there is a base
// check the value of the base by finding the index of the comma at parenIndex 1
var baseIndex = limits.trackInfo.characters.find((obj) => obj.character === ',' && obj.parenIndex === 1).index + 1;
var base = result.substring(baseIndex, limits[1]);
// if the base is 10, remove it (limits[1] - 3)
if (base === '10') {
result = result.substring(0, index - 1) + 'log' + result.substring(index + 1, limits[1] - 3) + ')' + result.substring(limits[1] + 1, result.length);
} else { // otherwise, do nothing
result = result.substring(0, index - 1) + 'log' + result.substring(index + 1, result.length);
}
}
}
return result;
};
// produces linear equation from two points
var linearPoints = function(x1, y1, x2, y2) {
var slope = ((y2 - y1) / (x2 - x1)).toFixed(10);
var yInt = (y1 - slope * x1).toFixed(10);
return {
equation: [Number(slope), Number(yInt)],
string: 'y=' + Number(slope) + 'x+' + Number(yInt),
r2: 1,
};
};
var isInt = (num) => f.round(num) === Number(num);
// 2D vector declaration
class Vector {
static vc = require('./parsers/vector.js');
// unit vector definitions
static i = new Vector('i', 1, 0);
static j = new Vector('j', 0, 1);
constructor(name, x1, y1, x2, y2) {
this.name = name;
if (x2 === undefined || y2 === undefined || x2 === null || y2 === null) { // if only two coordinates are provided; i know it looks confusing but just think about it lol
this.x1 = 0;
this.y1 = 0;
this.x2 = Number(x1);
this.y2 = Number(y1);
} else {
this.x1 = Number(x1);
this.y1 = Number(y1);
this.x2 = Number(x2);
this.y2 = Number(y2);
}
}
// convert an array to a vector
static fromArr(arr) {
return new Vector(arr[0], arr[1], arr[2], arr[3], arr[4]);
}
// returns a vector with a given magnitude and angle (polar form)
static fromPolar(name, mag, angle) {
return new Vector(name, mag * f.cos(angle), mag * f.sin(angle));
}
// returns the quadrant the vector component's head lies in (5 = x axis, 6 = y axis)
quadrant() {
var c = this.component();
if (c.x2 > 0) {
if (c.y2 > 0) {
return 1;
} else if (c.y2 < 0) {
return 4;
}
} else if (c.x2 < 0) {
if (c.y2 > 0) {
return 2;
} else if (c.y2 < 0) {
return 3;
}
}
if (c.x2 === 0) {
return 6;
} else if (c.y2 === 0) {
return 5;
}
}
// returns a vector's direction angle based on unit vector i
dirAngle(mode) {
angleMode(mode);
var q = this.quadrant();
var c = this.component();
var direction = f.atan(c.y2 / c.x2);
// add to direction based on the quadrant the vector's head lies in
if (c.x2 < 0) {
direction += ofCircle(0.5);
} else if (c.x2 >= 0 && c.y2 < 0) {
direction += ofCircle(1);
}
return direction;
}
// returns a vector's component form
component() {
return new Vector(this.name, this.x2 - this.x1, this.y2 - this.y1);
}
// returns a vector's magnitude
magnitude() {
return f.sqrt(f.pow(this.x2 - this.x1, 2) + f.pow(this.y2 - this.y1, 2));
}
// returns the vector's unit
unit() {
var c = this.component();
var m = c.magnitude();
return new Vector(c.name, c.x2 / m, c.y2 / m);
}
// returns dot product of two vectors
static dot(v1, v2) {
var vc1 = v1.component();
var vc2 = v2.component();
return vc1.x2 * vc2.x2 + vc1.y2 * vc2.y2;
}
// adds two vectors
static add(v1, v2) {
var vc1 = v1.component();
var vc2 = v2.component();
return new Vector('', vc1.x2 + vc2.x2, vc1.y2 + vc2.y2);
}
// subtracts two vectors
static subtract(v1, v2) {
var vc1 = v1.component();
var vc2 = v2.component();
return new Vector('', vc1.x2 - vc2.x2, vc1.y2 - vc2.y2);
}
// returns vector multiplied by a scalar
static multiply(v, s) {
return new Vector(v.name, v.x1 * s, v.y1 * s, v.x2 * s, v.y2 * s)
}
// evaluates a vector expression, accepting an array of defined vectors that this method can refer to
static evaluate(exp, definedVectors) {
var ast = Vector.vc.evaluate(exp, definedVectors);
// convert the result to a string
var str = '';
ast.forEach(function(token) {
if (token.type === 'VectorLiteral') {
str += '(' + token.value[0] + ', ' + token.value[1] + ')';
} else {
str += token.value;
}
});
return str;
}
// takes an array of arguments representing vectors and an array of defined vectors and checks if the vectors inside the first array are defined under the second array
static definedArray(arr, defines) {
var allDefined = true;
var defined = [];
arr.forEach(function(arg, index) {
defined[index] = false;
defines.forEach(function(v) {
if (arg === v.name) {
defined[index] = true;
}
});
});
defined.forEach(function(bool) {
if (!bool) {
allDefined = false;
}
});
return allDefined;
}
// takes an array of stored coordinates and converts them to vectors
// [name, x1, y1, x2, y2]
static convertArrays(arr) {
var vectors = [];
arr.forEach(function(list, index) {
vectors[index] = new Vector(list[0], list[1], list[2], list[3], list[4]);
});
return vectors;
}
// converts a vector to an array
static toArray(v) {
return [v.name, v.x1, v.y1, v.x2, v.y2];
}
// returns a nicely formatted string representing the vector
toString() {
return '(' + this.x1 + ', ' + this.y1 + ', ' + this.x2 + ', ' + this.y2 + ')';
}
}
// thrown when the user tries to add a nonexistent formula
class NoFormulaError extends Error {
constructor(message) {
super(message);
this.name = 'NoFormulaError';
}
}
// Formula declaration
class Formula {
constructor(id, ...args) {
this.step = 0;
this.id = id;
this.args = args;
if (id === 'igl') {
this.name = 'Ideal Gas Law';
this.leaveBlank = 1;
this.definition = 'P * V = n * R * T';
this.exclude = [{name: 'R', description: 'ideal gas constant (0.08206)'}];
this.vars = [{name: 'P', description: 'pressure (atm)'}, {name: 'V', description: 'volume (L)'}, {name: 'n', description: 'mole count'}, {name: 'T', description: 'temperature (K)'}];
} else if (id === 'hf') {
this.name = 'Heron\'s Formula';
this.leaveBlank = 0;
this.definition = 'p = (a + b + c) / 2\nA = sqrt(p * (p - a) * (p - b) * (p - c))';
this.exclude = [{name: 'p', description: 'half of perimeter'}, {name: 'A', description: 'area of triangle'}];
this.vars = [{name: 'a', description: 'side a'}, {name: 'b', description: 'side b'}, {name: 'c', description: 'side c'}];
} else if (id === 'pyt') {
this.name = 'Pythagorean Theorem';
this.leaveBlank = 1;
this.definition = 'a^2 + b^2 = c^2';
this.exclude = [];
this.vars = [{name: 'a', description: 'side a (leg)'}, {name: 'b', description: 'side b (leg)'}, {name: 'c', description: 'side c (hypotenuse)'}];
} else if (id === 'rps') {
this.name = 'Regular Polygon Area (from side)';
this.leaveBlank = 1;
this.definition = 'A = (s^2 * n) / (4 * tan([180 | π] / n))';
this.exclude = [];
this.vars = [{name: 'A', description: 'area of polygon'}, {name: 's', description: 'side length'}, {name: 'n', description: 'amount of sides'}];
} else if (id === 'rpr') {
this.name = 'Regular Polygon Area (from radius)';
this.leaveBlank = 1;
this.definition = 'A = r^2 * n * sin([360 | 2π] / n) / 2';
this.exclude = [];
this.vars = [{name: 'A', description: 'area of polygon'}, {name: 'r', description: 'radius (length from center to vertex)'}, {name: 'n', description: 'amount of sides'}];
} else if (id === 'rpa') {
this.name = 'Regular Polygon Area (from apothem)';
this.leaveBlank = 1;
this.definition = 'A = a^2 * n * tan([180 | π] / n)';
this.exclude = [];
this.vars = [{name: 'A', description: 'area of polygon'}, {name: 'a', description: 'apothem (length from center to midpoint of side)'}, {name: 'n', description: 'amount of sides'}];
} else if (id === 'sf') {
this.name = 'Slope Formula';
this.leaveBlank = 0;
this.definition = 's = (y_2 - y_1) / (x_2 - x_1)';
this.exclude = [{name: 's', description: 'slope'}];
this.vars = [{name: 'x_1', description: 'point 1 x'}, {name: 'y_1', description: 'point 1 y'}, {name: 'x_2', description: 'point 2 x'}, {name: 'y_2', description: 'point 2 y'}];
} else if (id === 'tlos') {
this.name = 'Law of Sines';
this.leaveBlank = 1;
this.definition = 'sin(A) / a = sin(B) / b';
this.exclude = [];
this.vars = [{name: 'A', description: 'angle A (opposite of side a)'}, {name: 'a', description: 'side a (opposite of angle A)'}, {name: 'B', description: 'angle B (opposite of side b)'}, {name: 'b', description: 'side b (opposite of angle B)'}];
} else if (id === 'tloc') {
this.name = 'Law of Cosines';
this.leaveBlank = 1;
this.definition = 'a^2 = b^2 + c^2 - 2 * b * c * cos(A)';
this.exclude = [];
this.vars = [{name: 'a', description: 'side a (opposite of angle A)'}, {name: 'b', description: 'side b'}, {name: 'c', description: 'side c'}, {name: 'A', description: 'angle A (opposite of side a)'}];
} else if (id === 'tts') {
this.name = 'Triangle Area';
this.leaveBlank = 1;
this.definition = 'A = (1 / 2) * s_1 * s_2 * sin(a_3)';
this.exclude = [];
this.vars = [{name: 'A', description: 'area'}, {name: 's_1', description: 'side 1'}, {name: 's_2', description: 'side 2'}, {name: 'a_3', description: 'angle 3 (angle opposite of side 3)'}];
} else {
throw new NoFormulaError(id + ' is an invalid formula ID.');
}
}
calculate() {
if (this.id === 'igl') { // ideal gas law
if (this.args[0] === undefined) { // finding P (pressure)
return this.args[2] * 0.08206 * this.args[3] / this.args[1];
} else if (this.args[1] === undefined) { // finding V (volume)
return this.args[2] * 0.08206 * this.args[3] / this.args[0];
} else if (this.args[2] === undefined) { // findind n (mole count)
return (this.args[0] * this.args[1]) / (0.08206 * this.args[3]);
} else if (this.args[3] === undefined) { // finding T (temperature)
return (this.args[0] * this.args[1]) / (this.args[2] * 0.08206);
}
} else if (this.id === 'hf') { // heron's formula
var p = (this.args[0] + this.args[1] + this.args[2]) / 2; // half of perimeter
return f.sqrt(p * (p - this.args[0]) * (p - this.args[1]) * (p - this.args[2])); // area
} else if (this.id === 'pyt') { // pythagorean theorem
if (this.args[0] === undefined) { // finding a
return f.sqrt(f.pow(this.args[2], 2) - f.pow(this.args[1], 2));
} else if (this.args[1] === undefined) { // finding b
return f.sqrt(f.pow(this.args[3], 2) - f.pow(this.args[0], 2));
} else if (this.args[2] === undefined) { // finding c (hypotenuse)
return f.sqrt(f.pow(this.args[0], 2) + f.pow(this.args[1], 2));
}
} else if (this.id === 'rps') { // regular polygon (from side)
if (this.args[0] === undefined) { // finding A (area)
return (f.pow(this.args[1], 2) * this.args[2]) / (4 * f.tan(ofCircle(0.5) / this.args[2]));
} else if (this.args[1] === undefined) { // finding s (side length)
return f.sqrt((this.args[0] * 4 * f.tan(ofCircle(0.5) / this.args[2])) / this.args[2]);
}
// impossible to find c
} else if (this.id === 'rpr') { // regular polygon (from radius)
if (this.args[0] === undefined) { // finding A (area)
return f.pow(this.args[1], 2) * this.args[2] * f.sin(ofCircle(1) / this.args[2]) / 2;
} else if (this.args[1] === undefined) { // finding r (radius)
return f.sqrt((this.args[0] * 2) / (this.args[2] * f.sin(ofCircle(1) / this.args[2])));
}
// impossible to find n
} else if (this.id === 'rpa') { // regular polygon (from apothem)
if (this.args[0] === undefined) { // finding A (area)
return f.pow(this.args[1], 2) * this.args[2] * f.tan(ofCircle(0.5) / this.args[2]);
} else if (this.args[1] === undefined) { // finding a (apothem)
return f.sqrt(this.args[0] / (this.args[2] * f.tan(ofCircle(0.5) / this.args[2])));
}
// impossible to find n
} else if (this.id === 'sf') { // slope formula
return (this.args[3] - this.args[1]) / (this.args[2] - this.args[0]);
} else if (this.id === 'tlos') { // law of sines
if (this.args[1] === undefined) { // finding a side
return this.args[3] * f.sin(this.args[0]) / f.sin(this.args[2]);
} else if (this.args[3] === undefined) {
return this.args[1] * f.sin(this.args[2]) / f.sin(this.args[0]);
} else if (this.args[0] === undefined) { // finding an angle
return f.asin(this.args[1] * f.sin(this.args[2]) / this.args[3]);
} else if (this.args[2] === undefined) {
return f.asin(this.args[3] * f.sin(this.args[0]) / this.args[1]);
}
} else if (this.id === 'tloc') { // law of cosines
if (this.args[0] === undefined) { // finding a side
return f.sqrt(f.pow(this.args[1], 2) + f.pow(this.args[2], 2) - 2 * this.args[1] * this.args[2] * f.cos(this.args[3]));
} else if (this.args[1] === undefined) {
return f.sqrt(f.pow(this.args[0], 2) - f.pow(this.args[2], 2) + 2 * this.args[1] * this.args[2] * f.cos(this.args[3]));
} else if (this.args[2] === undefined) {
return f.sqrt(f.pow(this.args[0], 2) - f.pow(this.args[1], 2) + 2 * this.args[1] * this.args[2] * f.cos(this.args[3]));
} else if (this.args[3] === undefined) { // getting the angle
return f.acos((f.pow(this.args[0], 2) - f.pow(this.args[1], 2) - f.pow(this.args[2], 2))/(-2 * this.args[1] * this.args[2]));
}
} else if (this.id === 'tts') { // triangle area
if (this.args[0] === undefined) { // finding area
return 0.5 * this.args[1] * this.args[2] * f.sin(this.args[3]);
} else if (this.args[1] === undefined) { // finding side 1
return (2 * this.args[0] * f.csc(this.args[3])) / this.args[2];
} else if (this.args[2] === undefined) { // finding side 2
return (2 * this.args[0] * f.csc(this.args[3])) / this.args[1];
} else if (this.args[3] === undefined) { // finding angle 3
return f.asin((2 * this.args[0]) / (this.args[1] * this.args[2]));
}
}
}
// returns the amount of arguments that were left undefined by the user (usually one)
undefinedCount() {
var undefinedCount = 0;
this.args.forEach(function(arg) {
if (arg === undefined) {
++undefinedCount;
}
});
return undefinedCount;
}
// returns a string of the variables
printVars() {
var str = '';
this.exclude.concat(this.vars).forEach(function(obj, index, arr) {
str += obj.name + ': ' + obj.description + (index < arr.length - 1 ? '\n' : '');
});
return str;
}
}
// implementation of a queue for searching the unit conversion / dimensional analysis conversion tree
class Queue {
constructor() {
this.items = [];
}
// add an item to the queue
enqueue(item) {
this.items.push(item);
}
// remove the head of the queue and return it
dequeue() {
return this.items.shift();
}
// returns the front of the queue
peek() {
return this.items[0];
}
// returns true if the queue is empty
empty() {
return this.items.length === 0;
}
}
// thrown when a path can't be found
class NoPathError extends Error {
constructor(message) {
super(message);
this.name = 'NoPathError';
}
}
// thrown when a unit is used that doesn't exist
class NoUnitError extends Error {
constructor(message) {
super(message);
this.name = 'NoUnitError';
}
}
// unit conversion through formulas (this class is for units that can't be converted using dimensional analysis, for example, temperature, or angles)
class UC {
static conversions = {
// angles
'deg': ['dtr(x) rad', '10x/9 grad'],
'rad': ['rtd(x) deg'],
'grad': ['0.9x deg'],
// temperature
'C': ['9x/5+32 F', 'x+273.15 K', '(9/5)(x+273.15) R', '(3/2)(100-x) De', '33x/100 N', '4x/5 Re', '21x/40+7.5 Ro'],
'F': ['(5/9)(x-32) C'],
'K': ['x-273.15 C'],
'R': ['(5/9)(x-491.67) C'],
'De': ['100-2x/3 C'],
'N': ['100x/33 C'],
'Re': ['5x/4 C'],
'Ro': ['(40/21)(x-7.5) C'],
};
// convert a single unit to another
static convert(quantity, start, end) {
if (!(start in UC.conversions) || !(end in UC.conversions)) {
throw new NoUnitError('The used ratios do not exist.');
}
// search for paths from the starting unit to the ending unit
var cameFrom = {};
var frontier = new Queue();
cameFrom[start] = undefined;
frontier.enqueue(start);
while (!frontier.empty()) {
var currentUnit = frontier.dequeue();
if (currentUnit === end) {
break;
}
if (UC.conversions[currentUnit]) {
UC.conversions[currentUnit].forEach(function(ratio) {
var arr = UC.stringToUnit(ratio);
if (!(arr[1] in cameFrom)) {
cameFrom[arr[1]] = currentUnit; // to get to ratio, come from currentUnit
frontier.enqueue(arr[1]);
}
});
}
}
// find path to end
var unitPath = [end];
var currentUnit = end;
while (cameFrom[currentUnit] !== undefined) {
unitPath.push(cameFrom[currentUnit]);
currentUnit = cameFrom[currentUnit];
}
unitPath.reverse();
console.log(start + ' ' + end);
console.log(unitPath);
if (unitPath[0] !== start || unitPath[unitPath.length - 1] !== end) {
throw new NoPathError('No valid conversion path was found.');
}
// follow the path to the end and convert using the formulas provided
var result = quantity;
var index = 0; // skip starting unit (we start with that already)
while (index < unitPath.length - 1) {
var currentUnit = unitPath[index];
var nextUnit = unitPath[index + 1];
var nextConversionFormula = UC.stringToUnit(UC.conversions[currentUnit].find(function(string) {
return UC.stringToUnit(string)[1] === nextUnit;
}));
result = evaluate(nextConversionFormula[0], {x: result});
++index;
}
return {
result: result,
path: unitPath,
};
}
// converts a string like 'dtr(x) rad' to [[tree], 'rad']
static stringToUnit(str) {
var arr = str.split(' ');
arr[0] = parse(arr[0]);
return arr;
}
// returns true if a unit exists in the conversions object
static exists(unit) {
return UC.conversions[unit] !== undefined;
}
}
// dimensional analysis
class DA {
static conversions = {
// length
'mi': ['1760 yd', '5280 ft', '1.609344 km'],
'yd': ['1/1760 mi', '3 ft', '36 in'],
'ft': ['1/3 yd', '12 in'],
'in': ['1/12 ft', '2.54 cm'],
'ly': ['scientific(9.4607304725808,15) m'],
'au': ['scientific(1.495978707,11) m'],
'nmi': ['1.852 km'],
'km': ['1000/1852 nmi', '1000 m', '0.621371192 mi'],
'm': ['1/9460730472580000 ly', '1/149597870700 au', '1/1000 km', '100 cm'],
'cm': ['1/100 m', '10 mm', '0.393700787 in'],
'cm^3': ['1/10000 m^3', '1000 mm^3', '0.061023743907999625 in^3', '1 mL'],
'mm': ['1/10 cm', '1000 um'],
'um': ['1/1000 mm', '1000 nm'],
'nm': ['1/1000 um', '10 A'],
'A': ['1/10 nm', '100 pm'],
'pm': ['1/100 A'],
// mass
'ton': ['2000 lb'], // us ton
'lb': ['1/2000 ton', '16 oz', '0.453592 kg', '454 g'],
'oz': ['1/16 lb', '28.3495231 g'],
't': ['1000 kg'], // metric ton (tonne)
'kg': ['1/1000 t', '1000 g', '2.20462 lb'],
'g': ['1/1000 kg', '100 cg', '0.00220462 lb', '0.0352739619 oz'],
'cg': ['1/100 g', '10 mg'],
'mg': ['1/10 cg', '1000 ug'],
'ug': ['1/1000 mg', 'scientific(6.02214086,17) amu'],
'amu': ['scientific(1.66,-18) ug'],
// area
'ha': ['100 are'],
'are': ['0.01 ha', '100 m^2'],
'm^2': ['1/1000000 km^2', '10000 cm^2', '1/100 are', 'scientific(1,28) b'],
'b': ['scientific(1,-28) m^2'],
'acre': ['4840 yd^2'],
'yd^2': ['1/3097600 mi^2', '9 ft^2', '1296 in^2', '1/4840 acre'],
// volume
'bu': ['8 gal'],
'gal': ['1/8 bu', '4 qt'],
'qt': ['1/4 gal', '2 pt', '0.946352946 L'],
'pt': ['1/2 qt', '2 c'],
'c': ['1/2 pt', '8 floz'],
'floz': ['1/8 c', '2 tbsp'],
'tbsp': ['1/2 floz', '3 tsp'],
'tsp': ['1/3 tbsp'],
'kL': ['1000 L'],
'L': ['1/1000 kL', '100 cL', '1000 mL', '1.05668821 qt'],
'cL': ['1/100 L', '10 mL'],
'mL': ['1/1000 L', '1/10 cL', '1000 uL', '1 cm^3'],
'uL': ['1/1000 mL'],
// time
'cen': ['10 dec'],
'dec': ['1/10 cen', '10 yr'],
'yr': ['1/10 dec', '52 wk'],
'wk': ['1/52 yr', '7 day'],
'day': ['1/7 wk', '24 hr'],
'hr': ['1/24 day', '60 min'],
'min': ['1/60 hr', '60 sec'],
'sec': ['1/60 min', '10 ds'],
'ds': ['1/10 sec', '100 ms'],
'ms': ['1/100 ds', '1000 us'],
'us': ['1/1000 ms', '1000 ns'],
'ns': ['1/1000 us'],
// amount of substance
'mol': ['scientific(6.02214086,23) atom'],
'atom': ['scientific(1.66053904,-24) mol'],
// pressure
'cmHg': ['10 mmHg', '10 Torr'],
'mmHg': ['1/10 cmHg', '0.00131579 atm', '1 Torr'],
'Torr': ['1 mmHg', '1/10 cmHg', '0.00131579 atm'],
'MPa': ['7500.62 mmHg', '1000 kPa'],
'kPa': ['1/1000 MPa', '1000 Pa'],
'Pa': ['1/1000 kPa', '0.000145038 psi'],
'psi': ['6894.76 Pa', '0.0689476 bar'],
'bar': ['14.5038 psi', '0.986923 atm'],
'atm': ['760 mmHg', '760 Torr', '1.01325 bar'],
// digital storage
'YiB': ['1000000000000/827180612553 YB'],
'YB': ['827180612553/1000000000000 YiB', '8 Yb'],
'Yb': ['1/8 YB', '125 ZB'],
'ZiB': ['500000000000/423516473627 ZB'],
'ZB': ['0.008 Yb', '423516473627/500000000000 ZiB', '8 Zb'],
'Zb': ['1/8 ZB', '125 EB'],
'EiB': ['250000000000/216840434497 EB'],
'EB': ['0.008 Zb', '216840434497/250000000000 EiB', '8 Eb'],
'Eb': ['1/8 EB', '125 PB'],
'PiB': ['10000000000/8881784197 PB'],
'PB': ['0.008 Eb', '8881784197/10000000000 PiB', '8 Pb'],
'Pb': ['1/8 PB', '125 TB'],
'TiB': ['1000000000000/909494701773 TB'],
'TB': ['0.008 Pb', '909494701773/1000000000000 TiB', '8 Tb'],
'Tb': ['1/8 TB', '125 GB'],
'GiB': ['200000000000/186264514923 GB'],
'GB': ['0.008 Tb', '186264514923/200000000000 GiB', '8 Gb'],
'Gb': ['1/8 GB', '125 MB'],
'MiB': ['16384/15625 MB'],
'MB': ['0.008 Gb', '15625/16384 MiB', '8 Mb'],
'Mb': ['1/8 MB', '125 KB'],
'KiB': ['1.024 KB'],
'KB': ['0.008 Mb', '125/128 KiB', '8 Kb'],
'Kb': ['1/8 KB', '125 byte'],
'byte': ['0.008 Kb', '8 bit'],
'bit': ['1/8 byte'],
};
// mark units that the program should not override with DA.additional()
static exceptions = ['m^2', 'yd^2', 'cm^3'];
static additional() {
Object.keys(DA.conversions).forEach(function(unit) {
if (!DA.exceptions.includes(unit)) {
for (var i = 2; i <= 4; ++i) {
if (!DA.exceptions.includes(unit + '^' + i)) {
DA.conversions[unit + '^' + i] = DA.conversions[unit].slice();
for (var j = 0; j < DA.conversions[unit].length; ++j) {
var raisedUnit = DA.conversions[unit][j];
var ratio = DA.stringToRatio(raisedUnit);
ratio[0] = f.pow(ratio[0], i);
ratio[1] = ratio[1] + '^' + i;
DA.conversions[unit + '^' + i][j] = DA.ratioToString(ratio);
}
}
}
}
});
}
// convert a single unit to another
static convertSingle(quantity, start, end, customRatios) {
start = start.replace(/[⁰¹²³⁴⁵⁶⁷⁸⁹]/g, (match) => '^' + ss[match]);
end = end.replace(/[⁰¹²³⁴⁵⁶⁷⁸⁹]/g, (match) => '^' + ss[match]);
var parsedCustom = [];
for (var i = 0; i < customRatios.length; ++i) {
parsedCustom[i] = DA.parseCustomRatio(customRatios[i]);
}
if (!(start in DA.conversions || DA.ratioInParsedCustom(start, parsedCustom)) || !(end in DA.conversions || DA.ratioInParsedCustom(end, parsedCustom))) {
throw new NoUnitError('The used ratios do not exist.');
}
// search for paths from the start ratio to the end ratio
var cameFrom = {};
var frontier = new Queue();
cameFrom[start] = undefined;
frontier.enqueue(start);
while (!frontier.empty()) {
var currentRatio = frontier.dequeue();
if (currentRatio === end) {
break;
}
// should be defined in all users
parsedCustom.forEach(function(obj) {
// go through generated object's keys (unit ratios)
for (var key in obj) {
if (key === currentRatio && !(obj[key][1] in cameFrom)) {
cameFrom[obj[key][1]] = currentRatio; // to get to ratio, come from currentRatio
frontier.enqueue(obj[key][1]);
}
}
});
if (DA.conversions[currentRatio]) {
DA.conversions[currentRatio].forEach(function(ratio) {