Repository navigation
Expand file tree
/
Copy pathUnit.js
More file actions
3284 lines (3001 loc) · 90.8 KB
/
Copy pathUnit.js
File metadata and controls
3284 lines (3001 loc) · 90.8 KB
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
10BC8
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
'use strict';
var endsWith = require('../../utils/string').endsWith;
var clone = require('../../utils/object').clone;
var constants = require('../../utils/bignumber/constants');
function factory (type, config, load, typed, math) {
var add = load(require('../../function/arithmetic/addScalar'));
var subtract = load(require('../../function/arithmetic/subtract'));
var multiply = load(require('../../function/arithmetic/multiplyScalar'));
var divide = load(require('../../function/arithmetic/divideScalar'));
var pow = load(require('../../function/arithmetic/pow'));
var abs = load(require('../../function/arithmetic/abs'));
var fix = load(require('../../function/arithmetic/fix'));
var round = load(require('../../function/arithmetic/round'));
var equal = load(require('../../function/relational/equal'));
var isNumeric = load(require('../../function/utils/isNumeric'));
var format = load(require('../../function/string/format'));
var getTypeOf = load(require('../../function/utils/typeof'));
var toNumber = load(require('../../type/number'));
var Complex = load(require('../../type/complex/Complex'));
/**
* A unit can be constructed in the following ways:
* var a = new Unit(value, name);
* var b = new Unit(null, name);
* var c = Unit.parse(str);
*
* Example usage:
* var a = new Unit(5, 'cm'); // 50 mm
* var b = Unit.parse('23 kg'); // 23 kg
* var c = math.in(a, new Unit(null, 'm'); // 0.05 m
* var d = new Unit(9.81, "m/s^2"); // 9.81 m/s^2
*
* @class Unit
* @constructor Unit
* @param {number | BigNumber | Fraction | Complex | boolean} [value] A value like 5.2
* @param {string} [name] A unit name like "cm" or "inch", or a derived unit of the form: "u1[^ex1] [u2[^ex2] ...] [/ u3[^ex3] [u4[^ex4]]]", such as "kg m^2/s^2", where each unit appearing after the forward slash is taken to be in the denominator. "kg m^2 s^-2" is a synonym and is also acceptable. Any of the units can include a prefix.
*/
function Unit(value, name) {
if (!(this instanceof Unit)) {
throw new Error('Constructor must be called with the new operator');
}
if (!(value == undefined || isNumeric(value) || type.isComplex(value))) {
throw new TypeError('First parameter in Unit constructor must be number, BigNumber, Fraction, Complex, or undefined');
}
if (name != undefined && (typeof name !== 'string' || name === '')) {
throw new TypeError('Second parameter in Unit constructor must be a string');
}
if (name != undefined) {
var u = Unit.parse(name);
this.units = u.units;
this.dimensions = u.dimensions;
}
else {
this.units = [
{
unit: UNIT_NONE,
prefix: PREFIXES.NONE, // link to a list with supported prefixes
power: 0
}
];
this.dimensions = [];
for(var i=0; i<BASE_DIMENSIONS.length; i++) {
this.dimensions[i] = 0;
}
}
this.value = (value != undefined) ? this._normalize(value) : null;
this.fixPrefix = false; // if true, function format will not search for the
// best prefix but leave it as initially provided.
// fixPrefix is set true by the method Unit.to
// The justification behind this is that if the constructor is explicitly called,
// the caller wishes the units to be returned exactly as he supplied.
this.isUnitListSimplified = true;
}
/**
* Attach type information
*/
Unit.prototype.type = 'Unit';
Unit.prototype.isUnit = true;
// private variables and functions for the Unit parser
var text, index, c;
function skipWhitespace() {
while (c == ' ' || c == '\t') {
next();
}
}
function isDigitDot(c) {
return ((c >= '0' && c <= '9') || c == '.');
}
function isDigit(c) {
return ((c >= '0' && c <= '9'));
}
function next() {
index++;
c = text.charAt(index);
}
function revert(oldIndex) {
index = oldIndex;
c = text.charAt(index);
}
function parseNumber() {
var number = '';
var oldIndex;
oldIndex = index;
if (c == '+') {
next();
}
else if (c == '-') {
number += c;
next();
}
if (!isDigitDot(c)) {
// a + or - must be followed by a digit
revert(oldIndex);
return null;
}
// get number, can have a single dot
if (c == '.') {
number += c;
next();
if (!isDigit(c)) {
// this is no legal number, it is just a dot
revert(oldIndex);
return null;
}
}
else {
while (isDigit(c)) {
number += c;
next();
}
if (c == '.') {
number += c;
next();
}
}
while (isDigit(c)) {
number += c;
next();
}
// check for exponential notation like "2.3e-4" or "1.23e50"
if (c == 'E' || c == 'e') {
// The grammar branches here. This could either be part of an exponent or the start of a unit that begins with the letter e, such as "4exabytes"
var tentativeNumber = '';
var tentativeIndex = index;
tentativeNumber += c;
next();
if (c == '+' || c == '-') {
tentativeNumber += c;
next();
}
// Scientific notation MUST be followed by an exponent (otherwise we assume it is not scientific notation)
if (!isDigit(c)) {
// The e or E must belong to something else, so return the number without the e or E.
revert(tentativeIndex);
return number;
}
// We can now safely say that this is scientific notation.
number = number + tentativeNumber;
while (isDigit(c)) {
number += c;
next();
}
}
return number;
}
function parseUnit() {
var unitName = '';
// Alphanumeric characters only; matches [a-zA-Z0-9]
var code = text.charCodeAt(index);
while ( (code >= 48 && code <= 57) ||
(code >= 65 && code <= 90) ||
(code >= 97 && code <= 122)) {
unitName += c;
next();
code = text.charCodeAt(index);
}
// Must begin with [a-zA-Z]
code = unitName.charCodeAt(0);
if ((code >= 65 && code <= 90) ||
(code >= 97 && code <= 122)) {
return unitName || null;
}
else {
return null;
}
}
function parseCharacter(toFind) {
if (c === toFind) {
next();
return toFind;
}
else {
return null;
}
}
/**
* Parse a string into a unit. The value of the unit is parsed as number,
* BigNumber, or Fraction depending on the math.js config setting `number`.
*
* Throws an exception if the provided string does not contain a valid unit or
* cannot be parsed.
* @memberof Unit
* @param {string} str A string like "5.2 inch", "4e2 cm/s^2"
* @return {Unit} unit
*/
Unit.parse = function (str, options) {
options = options || {};
text = str;
index = -1;
c = '';
if (typeof text !== 'string') {
throw new TypeError('Invalid argument in Unit.parse, string expected');
}
var unit = new Unit();
unit.units = [];
// A unit should follow this pattern:
// [number]unit[^number] [unit[^number]]...[/unit[^number] [unit[^number]]]
// Rules:
// number is any floating point number.
// unit is any alphanumeric string beginning with an alpha. Units with names like e3 should be avoided because they look like the exponent of a floating point number!
// The string may optionally begin with a number.
// Each unit may optionally be followed by ^number.
// Whitespace or a forward slash is recommended between consecutive units, although the following technically is parseable:
// 2m^2kg/s^2
// it is not good form. If a unit starts with e, then it could be confused as a floating point number:
// 4erg
next();
skipWhitespace();
// Optional number at the start of the string
var valueStr = parseNumber();
var value = null;
if(valueStr) {
if (config.number === 'BigNumber') {
value = new type.BigNumber(valueStr);
}
else if (config.number === 'Fraction') {
value = new type.Fraction(valueStr);
}
else { // number
value = parseFloat(valueStr);
}
}
skipWhitespace(); // Whitespace is not required here
// Next, we read any number of unit[^number]
var powerMultiplierCurrent = 1;
var expectingUnit = false;
// Stack to keep track of powerMultipliers applied to each parentheses group
var powerMultiplierStack = [];
// Running product of all elements in powerMultiplierStack
var powerMultiplierStackProduct = 1;
while (true) {
skipWhitespace();
// Check for and consume opening parentheses, pushing powerMultiplierCurrent to the stack
// A '(' will always appear directly before a unit.
while (c === '(') {
powerMultiplierStack.push(powerMultiplierCurrent);
powerMultiplierStackProduct *= powerMultiplierCurrent;
powerMultiplierCurrent = 1;
next();
skipWhitespace();
}
// Is there something here?
if(c) {
var oldC = c;
var uStr = parseUnit();
if(uStr == null) {
throw new SyntaxError('Unexpected "' + oldC + '" in "' + text + '" at index ' + index.toString());
}
}
else {
// End of input.
break;
}
// Verify the unit exists and get the prefix (if any)
var res = _findUnit(uStr);
if(res == null) {
// Unit not found.
throw new SyntaxError('Unit "' + uStr + '" not found.');
}
var power = powerMultiplierCurrent * powerMultiplierStackProduct;
// Is there a "^ number"?
skipWhitespace();
if (parseCharacter('^')) {
skipWhitespace();
var p = parseNumber();
if(p == null) {
// No valid number found for the power!
throw new SyntaxError('In "' + str + '", "^" must be followed by a floating-point number');
}
power *= p;
}
// Add the unit to the list
unit.units.push( {
unit: res.unit,
prefix: res.prefix,
power: power
});
for(var i=0; i<BASE_DIMENSIONS.length; i++) {
unit.dimensions[i] += (res.unit.dimensions[i] || 0) * power;
}
// Check for and consume closing parentheses, popping from the stack.
// A ')' will always follow a unit.
skipWhitespace();
while (c === ')') {
if(powerMultiplierStack.length === 0) {
throw new SyntaxError('Unmatched ")" in "' + text + '" at index ' + index.toString());
}
powerMultiplierStackProduct /= powerMultiplierStack.pop();
next();
skipWhitespace();
}
// "*" and "/" should mean we are expecting something to come next.
// Is there a forward slash? If so, negate powerMultiplierCurrent. The next unit or paren group is in the denominator.
expectingUnit = false;
if (parseCharacter('*')) {
// explicit multiplication
powerMultiplierCurrent = 1;
expectingUnit = true;
}
else if (parseCharacter('/')) {
// division
powerMultiplierCurrent = -1;
expectingUnit = true;
}
else {
// implicit multiplication
powerMultiplierCurrent = 1;
}
// Replace the unit into the auto unit system
if(res.unit.base) {
var baseDim = res.unit.base.key;
UNIT_SYSTEMS.auto[baseDim] = {
unit: res.unit,
prefix: res.prefix
};
}
}
// Has the string been entirely consumed?
skipWhitespace();
if(c) {
throw new SyntaxError('Could not parse: "' + str + '"');
}
// Is there a trailing slash?
if(expectingUnit) {
throw new SyntaxError('Trailing characters: "' + str + '"');
}
// Is the parentheses stack empty?
if(powerMultiplierStack.length !== 0) {
throw new SyntaxError('Unmatched "(" in "' + text + '"');
}
// Are there any units at all?
if(unit.units.length == 0 && !options.allowNoUnits) {
throw new SyntaxError('"' + str + '" contains no units');
}
unit.value = (value != undefined) ? unit._normalize(value) : null;
return unit;
};
/**
* create a copy of this unit
* @memberof Unit
* @return {Unit} Returns a cloned version of the unit
*/
Unit.prototype.clone = function () {
var unit = new Unit();
unit.fixPrefix = this.fixPrefix;
unit.isUnitListSimplified = this.isUnitListSimplified;
unit.value = clone(this.value);
unit.dimensions = this.dimensions.slice(0);
unit.units = [];
for(var i = 0; i < this.units.length; i++) {
unit.units[i] = { };
for (var p in this.units[i]) {
if (this.units[i].hasOwnProperty(p)) {
unit.units[i][p] = this.units[i][p];
}
}
}
return unit;
};
/**
* Return whether the unit is derived (such as m/s, or cm^2, but not N)
* @memberof Unit
* @return {boolean} True if the unit is derived
*/
Unit.prototype._isDerived = function() {
if(this.units.length === 0) {
return false;
}
return this.units.length > 1 || Math.abs(this.units[0].power - 1.0) > 1e-15;
};
/**
* Normalize a value, based on its currently set unit(s)
* @memberof Unit
* @param {number | BigNumber | Fraction | boolean} value
* @return {number | BigNumber | Fraction | boolean} normalized value
* @private
*/
Unit.prototype._normalize = function (value) {
var unitValue, unitOffset, unitPower, unitPrefixValue;
var convert;
if (value == null || this.units.length === 0) {
return value;
}
else if (this._isDerived()) {
// This is a derived unit, so do not apply offsets.
// For example, with J kg^-1 degC^-1 you would NOT want to apply the offset.
var res = value;
convert = Unit._getNumberConverter(getTypeOf(value)); // convert to Fraction or BigNumber if needed
for(var i=0; i < this.units.length; i++) {
unitValue = convert(this.units[i].unit.value);
unitPrefixValue = convert(this.units[i].prefix.value);
unitPower = convert(this.units[i].power);
res = multiply(res, pow(multiply(unitValue, unitPrefixValue), unitPower));
}
return res;
}
else {
// This is a single unit of power 1, like kg or degC
convert = Unit._getNumberConverter(getTypeOf(value)); // convert to Fraction or BigNumber if needed
unitValue = convert(this.units[0].unit.value);
unitOffset = convert(this.units[0].unit.offset);
unitPrefixValue = convert(this.units[0].prefix.value);
return multiply(add(value, unitOffset), multiply(unitValue, unitPrefixValue));
}
};
/**
* Denormalize a value, based on its currently set unit(s)
* @memberof Unit
* @param {number} value
* @param {number} [prefixValue] Optional prefix value to be used (ignored if this is a derived unit)
* @return {number} denormalized value
* @private
*/
Unit.prototype._denormalize = function (value, prefixValue) {
var unitValue, unitOffset, unitPower, unitPrefixValue;
var convert;
if (value == null || this.units.length === 0) {
return value;
}
else if (this._isDerived()) {
// This is a derived unit, so do not apply offsets.
// For example, with J kg^-1 degC^-1 you would NOT want to apply the offset.
// Also, prefixValue is ignored--but we will still use the prefix value stored in each unit, since kg is usually preferable to g unless the user decides otherwise.
var res = value;
convert = Unit._getNumberConverter(getTypeOf(value)); // convert to Fraction or BigNumber if needed
for (var i = 0; i < this.units.length; i++) {
unitValue = convert(this.units[i].unit.value);
unitPrefixValue = convert(this.units[i].prefix.value);
unitPower = convert(this.units[i].power);
res = divide(res, pow(multiply(unitValue, unitPrefixValue), unitPower));
}
return res;
}
else {
// This is a single unit of power 1, like kg or degC
convert = Unit._getNumberConverter(getTypeOf(value)); // convert to Fraction or BigNumber if needed
unitValue = convert(this.units[0].unit.value);
unitPrefixValue = convert(this.units[0].prefix.value);
unitOffset = convert(this.units[0].unit.offset);
if (prefixValue == undefined) {
return subtract(divide(divide(value, unitValue), unitPrefixValue), unitOffset);
}
else {
return subtract(divide(divide(value, unitValue), prefixValue), unitOffset);
}
}
};
/**
* Find a unit from a string
* @memberof Unit
* @param {string} str A string like 'cm' or 'inch'
* @returns {Object | null} result When found, an object with fields unit and
* prefix is returned. Else, null is returned.
* @private
*/
function _findUnit(str) {
// First, match units names exactly. For example, a user could define 'mm' as 10^-4 m, which is silly, but then we would want 'mm' to match the user-defined unit.
if(UNITS.hasOwnProperty(str)) {
var unit = UNITS[str];
var prefix = unit.prefixes[''];
return {
unit: unit,
prefix: prefix
}
}
for (var name in UNITS) {
if (UNITS.hasOwnProperty(name)) {
if (endsWith(str, name)) {
var unit = UNITS[name];
var prefixLen = (str.length - name.length);
var prefixName = str.substring(0, prefixLen);
var prefix = unit.prefixes.hasOwnProperty(prefixName)
? unit.prefixes[prefixName]
: undefined;
if (prefix !== undefined) {
// store unit, prefix, and value
return {
unit: unit,
prefix: prefix
};
}
}
}
}
return null;
}
/**
* Test if the given expression is a unit.
* The unit can have a prefix but cannot have a value.
* @memberof Unit
* @param {string} name A string to be tested whether it is a value less unit.
* The unit can have prefix, like "cm"
* @return {boolean} true if the given string is a unit
*/
Unit.isValuelessUnit = function (name) {
return (_findUnit(name) != null);
};
/**
* check if this unit has given base unit
* If this unit is a derived unit, this will ALWAYS return false, since by definition base units are not derived.
* @memberof Unit
* @param {BASE_UNITS | string | undefined} base
*/
Unit.prototype.hasBase = function (base) {
if(typeof(base) === "string") {
base = BASE_UNITS[base];
}
if(!base)
return false;
// All dimensions must be the same
for(var i=0; i<BASE_DIMENSIONS.length; i++) {
if (Math.abs((this.dimensions[i] || 0) - (base.dimensions[i] || 0)) > 1e-12) {
return false;
}
}
return true;
};
/**
* Check if this unit has a base or bases equal to another base or bases
* For derived units, the exponent on each base also must match
* @memberof Unit
* @param {Unit} other
* @return {boolean} true if equal base
*/
Unit.prototype.equalBase = function (other) {
// All dimensions must be the same
for(var i=0; i<BASE_DIMENSIONS.length; i++) {
if (Math.abs((this.dimensions[i] || 0) - (other.dimensions[i] || 0)) > 1e-12) {
return false;
}
}
return true;
};
/**
* Check if this unit equals another unit
* @memberof Unit
* @param {Unit} other
* @return {boolean} true if both units are equal
*/
Unit.prototype.equals = function (other) {
return (this.equalBase(other) && equal(this.value, other.value));
};
/**
* Multiply this unit with another one
* @memberof Unit
* @param {Unit} other
* @return {Unit} product of this unit and the other unit
*/
Unit.prototype.multiply = function (other) {
var res = this.clone();
for(var i = 0; i<BASE_DIMENSIONS.length; i++) {
// Dimensions arrays may be of different lengths. Default to 0.
res.dimensions[i] = (this.dimensions[i] || 0) + (other.dimensions[i] || 0);
}
// Append other's units list onto res (simplify later in Unit.prototype.format)
for(var i=0; i<other.units.length; i++) {
// Make a deep copy
var inverted = {};
for(var key in other.units[i]) {
inverted[key] = other.units[i][key];
}
res.units.push(inverted);
}
// If at least one operand has a value, then the result should also have a value
if(this.value != null || other.value != null) {
var valThis = this.value == null ? this._normalize(1) : this.value;
var valOther = other.value == null ? other._normalize(1) : other.value;
res.value = multiply(valThis, valOther);
}
else {
res.value = null;
}
// Trigger simplification of the unit list at some future time
res.isUnitListSimplified = false;
return getNumericIfUnitless(res);
};
/**
* Divide this unit by another one
* @memberof Unit
* @param {Unit} other
* @return {Unit} result of dividing this unit by the other unit
*/
Unit.prototype.divide = function (other) {
var res = this.clone();
for(var i=0; i<BASE_DIMENSIONS.length; i++) {
// Dimensions arrays may be of different lengths. Default to 0.
res.dimensions[i] = (this.dimensions[i] || 0) - (other.dimensions[i] || 0);
}
// Invert and append other's units list onto res (simplify later in Unit.prototype.format)
for(var i=0; i<other.units.length; i++) {
// Make a deep copy
var inverted = {};
for(var key in other.units[i]) {
inverted[key] = other.units[i][key];
}
inverted.power = -inverted.power;
res.units.push(inverted);
}
// If at least one operand has a value, the result should have a value
if (this.value != null || other.value != null) {
var valThis = this.value == null ? this._normalize(1) : this.value;
var valOther = other.value == null ? other._normalize(1) : other.value;
res.value = divide(valThis, valOther);
}
else {
res.value = null;
}
// Trigger simplification of the unit list at some future time
res.isUnitListSimplified = false;
return getNumericIfUnitless(res);
};
/**
* Calculate the power of a unit
* @memberof Unit
* @param {number | Fraction | BigNumber} p
* @returns {Unit} The result: this^p
*/
Unit.prototype.pow = function (p) {
var res = this.clone();
for(var i=0; i<BASE_DIMENSIONS.length; i++) {
// Dimensions arrays may be of different lengths. Default to 0.
res.dimensions[i] = (this.dimensions[i] || 0) * p;
}
// Adjust the power of each unit in the list
for(var i=0; i<res.units.length; i++) {
res.units[i].power *= p;
}
if(res.value != null) {
res.value = pow(res.value, p);
// only allow numeric output, we don't want to return a Complex number
//if (!isNumeric(res.value)) {
// res.value = NaN;
//}
// Update: Complex supported now
}
else {
res.value = null;
}
// Trigger lazy evaluation of the unit list
res.isUnitListSimplified = false;
return getNumericIfUnitless(res);
};
/**
* Return the numeric value of this unit if it is dimensionless, has a value, and config.predictable == false; or the original unit otherwise
* @param {Unit} unit
* @returns {number | Fraction | BigNumber | Unit} The numeric value of the unit if conditions are met, or the original unit otherwise
*/
var getNumericIfUnitless = function(unit) {
if(unit.equalBase(BASE_UNITS.NONE) && unit.value !== null && !config.predictable) {
return unit.value;
}
else {
return unit;
}
}
/**
* Calculate the absolute value of a unit
* @memberof Unit
* @param {number | Fraction | BigNumber} x
* @returns {Unit} The result: |x|, absolute value of x
*/
Unit.prototype.abs = function () {
// This gives correct, but unexpected, results for units with an offset.
// For example, abs(-283.15 degC) = -263.15 degC !!!
var ret = this.clone();
ret.value = abs(ret.value);
for(var i in ret.units) {
if(ret.units[i].unit.name === 'VA' || ret.units[i].unit.name === 'VAR') {
ret.units[i].unit = UNITS["W"];
}
}
return ret;
};
/**
* Convert the unit to a specific unit name.
* @memberof Unit
* @param {string | Unit} valuelessUnit A unit without value. Can have prefix, like "cm"
* @returns {Unit} Returns a clone of the unit with a fixed prefix and unit.
*/
Unit.prototype.to = function (valuelessUnit) {
var other;
var value = this.value == null ? this._normalize(1) : this.value;
if (typeof valuelessUnit === 'string') {
//other = new Unit(null, valuelessUnit);
other = Unit.parse(valuelessUnit);
if (!this.equalBase(other)) {
throw new Error('Units do not match');
}
if (other.value !== null) {
throw new Error('Cannot convert to a unit with a value');
}
other.value = clone(value);
other.fixPrefix = true;
other.isUnitListSimplified = true;
return other;
}
else if (type.isUnit(valuelessUnit)) {
if (!this.equalBase(valuelessUnit)) {
throw new Error('Units do not match');
}
if (valuelessUnit.value !== null) {
throw new Error('Cannot convert to a unit with a value');
}
other = valuelessUnit.clone();
other.value = clone(value);
other.fixPrefix = true;
other.isUnitListSimplified = true;
return other;
}
else {
throw new Error('String or Unit expected as parameter');
}
};
/**
* Return the value of the unit when represented with given valueless unit
* @memberof Unit
* @param {string | Unit} valuelessUnit For example 'cm' or 'inch'
* @return {number} Returns the unit value as number.
*/
// TODO: deprecate Unit.toNumber? It's always better to use toNumeric
Unit.prototype.toNumber = function (valuelessUnit) {
return toNumber(this.toNumeric(valuelessUnit));
};
/**
* Return the value of the unit in the original numeric type
* @memberof Unit
* @param {string | Unit} valuelessUnit For example 'cm' or 'inch'
* @return {number | BigNumber | Fraction} Returns the unit value
*/
Unit.prototype.toNumeric = function (valuelessUnit) {
var other = this;
if(valuelessUnit) {
// Allow getting the numeric value without converting to a different unit
other = this.to(valuelessUnit);
}
other.simplifyUnitListLazy();
if(other._isDerived()) {
return other._denormalize(other.value);
}
else {
return other._denormalize(other.value, other.units[0].prefix.value);
}
};
/**
* Get a string representation of the unit.
* @memberof Unit
* @return {string}
*/
Unit.prototype.toString = function () {
return this.format();
};
/**
* Get a JSON representation of the unit
* @memberof Unit
* @returns {Object} Returns a JSON object structured as:
* `{"mathjs": "Unit", "value": 2, "unit": "cm", "fixPrefix": false}`
*/
Unit.prototype.toJSON = function () {
return {
mathjs: 'Unit',
value: this._denormalize(this.value),
unit: this.formatUnits(),
fixPrefix: this.fixPrefix
};
};
/**
* Instantiate a Unit from a JSON object
* @memberof Unit
* @param {Object} json A JSON object structured as:
* `{"mathjs": "Unit", "value": 2, "unit": "cm", "fixPrefix": false}`
* @return {Unit}
*/
Unit.fromJSON = function (json) {
var unit = new Unit(json.value, json.unit);
unit.fixPrefix = json.fixPrefix || false;
return unit;
};
/**
* Returns the string representation of the unit.
* @memberof Unit
* @return {string}
*/
Unit.prototype.valueOf = Unit.prototype.toString;
/**
* Attempt to simplify the list of units for this unit according to the dimensions array and the current unit system. After the call, this Unit will contain a list of the "best" units for formatting.
* Intended to be evaluated lazily. You must set isUnitListSimplified = false before the call! After the call, isUnitListSimplified will be set to true.
*/
Unit.prototype.simplifyUnitListLazy = function() {
if (this.isUnitListSimplified || this.value == null) {
return;
}
var proposedUnitList = [];
// Search for a matching base
var matchingBase;
for(var key in currentUnitSystem) {
if(this.hasBase(BASE_UNITS[key])) {
matchingBase = key;
break;
}
}
if(matchingBase === 'NONE')
{
this.units = [];
}
else {
var matchingUnit;
if(matchingBase) {
// Does the unit system have a matching unit?
if(currentUnitSystem.hasOwnProperty(matchingBase)) {
matchingUnit = currentUnitSystem[matchingBase];
}
}
var value;
var str;
if(matchingUnit) {
this.units = [{
unit: matchingUnit.unit,
prefix: matchingUnit.prefix,
power: 1.0
}];
}
else {
// Multiple units or units with powers are formatted like this:
// 5 (kg m^2) / (s^3 mol)
// Build an representation from the base units of the current unit system
var missingBaseDim = false;
for(var i=0; i<BASE_DIMENSIONS.length; i++) {
var baseDim = BASE_DIMENSIONS[i];
if(Math.abs(this.dimensions[i] || 0) > 1e-12) {
if(currentUnitSystem.hasOwnProperty(baseDim)) {
proposedUnitList.push({
unit: currentUnitSystem[baseDim].unit,
prefix: currentUnitSystem[baseDim].prefix,
power: this.dimensions[i] || 0
});
}
else {
missingBaseDim = true;
}
}
}
// Is the proposed unit list "simpler" than the existing one?
if(proposedUnitList.length < this.units.length && !missingBaseDim) {
// Replace this unit list with the proposed list
this.units = proposedUnitList;
}
}
}
this.isUnitListSimplified = true;
};
Unit.prototype.toSI = function() {
var ret = this.clone();