-
-
Notifications
You must be signed in to change notification settings - Fork 1.3k
Expand file tree
/
Copy pathUnit.js
More file actions
3412 lines (3148 loc) · 96 KB
/
Unit.js
File metadata and controls
3412 lines (3148 loc) · 96 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
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
import { isComplex, isUnit, typeOf } from '../../utils/is.js'
import { factory } from '../../utils/factory.js'
import { memoize } from '../../utils/function.js'
import { endsWith } from '../../utils/string.js'
import { clone, hasOwnProperty } from '../../utils/object.js'
import { createBigNumberPi as createPi } from '../../utils/bignumber/constants.js'
const name = 'Unit'
const dependencies = [
'?on',
'config',
'addScalar',
'subtractScalar',
'multiplyScalar',
'divideScalar',
'pow',
'abs',
'fix',
'round',
'equal',
'isNumeric',
'format',
'number',
'Complex',
'BigNumber',
'Fraction'
]
export const createUnitClass = /* #__PURE__ */ factory(name, dependencies, ({
on,
config,
addScalar,
subtractScalar,
multiplyScalar,
divideScalar,
pow,
abs,
fix,
round,
equal,
isNumeric,
format,
number,
Complex,
BigNumber,
Fraction
}) => {
const toNumber = number
const fixPrefixDefault = false
const skipAutomaticSimplificationDefault = true
/**
* A unit can be constructed in the following ways:
*
* const a = new Unit(value, valuelessUnit)
* const b = new Unit(null, valuelessUnit)
* const c = Unit.parse(str)
*
* Example usage:
*
* const a = new Unit(5, 'cm') // 50 mm
* const b = Unit.parse('23 kg') // 23 kg
* const c = math.in(a, new Unit(null, 'm') // 0.05 m
* const 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 | Unit} valuelessUnit A unit without value. Can have prefix, like "cm"
*/
function Unit (value, valuelessUnit) {
if (!(this instanceof Unit)) {
throw new Error('Constructor must be called with the new operator')
}
if (!(value === null || value === undefined || isNumeric(value) || isComplex(value))) {
throw new TypeError('First parameter in Unit constructor must be number, BigNumber, Fraction, Complex, or undefined')
}
this.fixPrefix = fixPrefixDefault // 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 supplied.
this.skipAutomaticSimplification = skipAutomaticSimplificationDefault
if (valuelessUnit === undefined) {
this.units = []
this.dimensions = BASE_DIMENSIONS.map(x => 0)
} else if (typeof valuelessUnit === 'string') {
const u = Unit.parse(valuelessUnit)
this.units = u.units
this.dimensions = u.dimensions
} else if (isUnit(valuelessUnit) && valuelessUnit.value === null) {
// clone from valuelessUnit
this.fixPrefix = valuelessUnit.fixPrefix
this.skipAutomaticSimplification = valuelessUnit.skipAutomaticSimplification
this.dimensions = valuelessUnit.dimensions.slice(0)
this.units = valuelessUnit.units.map(u => Object.assign({}, u))
} else {
throw new TypeError('Second parameter in Unit constructor must be a string or valueless Unit')
}
this.value = this._normalize(value)
}
/**
* Attach type information
*/
Object.defineProperty(Unit, 'name', { value: 'Unit' })
Unit.prototype.constructor = Unit
Unit.prototype.type = 'Unit'
Unit.prototype.isUnit = true
// private variables and functions for the Unit parser
let 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 () {
let number = ''
const 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"
let tentativeNumber = ''
const 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 () {
let unitName = ''
// Alphanumeric characters only; matches [a-zA-Z0-9]
while (isDigit(c) || Unit.isValidAlpha(c)) {
unitName += c
next()
}
// Must begin with [a-zA-Z]
const firstC = unitName.charAt(0)
if (Unit.isValidAlpha(firstC)) {
return unitName
} 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')
}
const unit = new Unit()
unit.units = []
let powerMultiplierCurrent = 1
let expectingUnit = false
// A unit should follow this pattern:
// [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
const valueStr = parseNumber()
let value = null
if (valueStr) {
if (config.number === 'BigNumber') {
value = new BigNumber(valueStr)
} else if (config.number === 'Fraction') {
try {
// not all numbers can be turned in Fractions, for example very small numbers not
value = new Fraction(valueStr)
} catch (err) {
value = parseFloat(valueStr)
}
} else { // number
value = parseFloat(valueStr)
}
skipWhitespace() // Whitespace is not required here
// handle multiplication or division right after the value, like '1/s'
if (parseCharacter('*')) {
powerMultiplierCurrent = 1
expectingUnit = true
} else if (parseCharacter('/')) {
powerMultiplierCurrent = -1
expectingUnit = true
}
}
// Stack to keep track of powerMultipliers applied to each parentheses group
const powerMultiplierStack = []
// Running product of all elements in powerMultiplierStack
let 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?
let uStr
if (c) {
const oldC = c
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)
const res = _findUnit(uStr)
if (res === null) {
// Unit not found.
throw new SyntaxError('Unit "' + uStr + '" not found.')
}
let power = powerMultiplierCurrent * powerMultiplierStackProduct
// Is there a "^ number"?
skipWhitespace()
if (parseCharacter('^')) {
skipWhitespace()
const 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
})
for (let 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) {
const 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 () {
const unit = new Unit()
unit.fixPrefix = this.fixPrefix
unit.skipAutomaticSimplification = this.skipAutomaticSimplification
unit.value = clone(this.value)
unit.dimensions = this.dimensions.slice(0)
unit.units = []
for (let i = 0; i < this.units.length; i++) {
unit.units[i] = { }
for (const p in this.units[i]) {
if (hasOwnProperty(this.units[i], p)) {
unit.units[i][p] = this.units[i][p]
}
}
}
return unit
}
/**
* Return the type of the value of this unit
*
* @memberof Unit
* @return {string} type of the value of the unit
*/
Unit.prototype.valueType = function () {
return typeOf(this.value)
}
/**
* 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
* @private
*/
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) {
if (value === null || value === undefined || this.units.length === 0) {
return value
}
let res = value
const convert = Unit._getNumberConverter(typeOf(value)) // convert to Fraction or BigNumber if needed
for (let i = 0; i < this.units.length; i++) {
const unitValue = convert(this.units[i].unit.value)
const unitPrefixValue = convert(this.units[i].prefix.value)
const unitPower = convert(this.units[i].power)
res = multiplyScalar(res, pow(multiplyScalar(unitValue, unitPrefixValue), unitPower))
}
return res
}
/**
* 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) {
if (value === null || value === undefined || this.units.length === 0) {
return value
}
let res = value
const convert = Unit._getNumberConverter(typeOf(value)) // convert to Fraction or BigNumber if needed
for (let i = 0; i < this.units.length; i++) {
const unitValue = convert(this.units[i].unit.value)
const unitPrefixValue = convert(this.units[i].prefix.value)
const unitPower = convert(this.units[i].power)
res = divideScalar(res, pow(multiplyScalar(unitValue, unitPrefixValue), unitPower))
}
return res
}
/**
* 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
*/
const _findUnit = memoize((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 (hasOwnProperty(UNITS, str)) {
const unit = UNITS[str]
const prefix = unit.prefixes['']
return { unit, prefix }
}
for (const name in UNITS) {
if (hasOwnProperty(UNITS, name)) {
if (endsWith(str, name)) {
const unit = UNITS[name]
const prefixLen = (str.length - name.length)
const prefixName = str.substring(0, prefixLen)
const prefix = hasOwnProperty(unit.prefixes, prefixName)
? unit.prefixes[prefixName]
: undefined
if (prefix !== undefined) {
// store unit, prefix, and value
return { unit, prefix }
}
}
}
}
return null
}, { hasher: (args) => args[0], limit: 100 })
/**
* 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_UNIT | 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 (let 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 (let 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 or with a scalar
* @memberof Unit
* @param {Unit} other
* @return {Unit} product of this unit and the other unit
*/
Unit.prototype.multiply = function (_other) {
const res = this.clone()
const other = isUnit(_other) ? _other : new Unit(_other)
for (let 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
for (let i = 0; i < other.units.length; i++) {
// Make a shallow copy of every unit
const inverted = {
...other.units[i]
}
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) {
const valThis = this.value === null ? this._normalize(one(other.value)) : this.value
const valOther = other.value === null ? other._normalize(one(this.value)) : other.value
res.value = multiplyScalar(valThis, valOther)
} else {
res.value = null
}
if (isUnit(_other)) {
res.skipAutomaticSimplification = false
}
return getNumericIfUnitless(res)
}
/**
* Divide a number by this unit
*
* @memberof Unit
* @param {numeric} numerator
* @param {unit} result of dividing numerator by this unit
*/
Unit.prototype.divideInto = function (numerator) {
return new Unit(numerator).divide(this)
}
/**
* Divide this unit by another one
* @memberof Unit
* @param {Unit | numeric} other
* @return {Unit} result of dividing this unit by the other unit
*/
Unit.prototype.divide = function (_other) {
const res = this.clone()
const other = isUnit(_other) ? _other : new Unit(_other)
for (let 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
for (let i = 0; i < other.units.length; i++) {
// Make a shallow copy of every unit
const inverted = {
...other.units[i],
power: -other.units[i].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) {
const valThis = this.value === null ? this._normalize(one(other.value)) : this.value
const valOther = other.value === null ? other._normalize(one(this.value)) : other.value
res.value = divideScalar(valThis, valOther)
} else {
res.value = null
}
if (isUnit(_other)) {
res.skipAutomaticSimplification = 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) {
const res = this.clone()
for (let 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 (let 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
}
res.skipAutomaticSimplification = 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
*/
function getNumericIfUnitless (unit) {
if (unit.equalBase(BASE_UNITS.NONE) && unit.value !== null && !config.predictable) {
return unit.value
} else {
return unit
}
}
/**
* Create a value one with the numeric type of `typeOfValue`.
* For example, `one(new BigNumber(3))` returns `BigNumber(1)`
* @param {number | Fraction | BigNumber} typeOfValue
* @returns {number | Fraction | BigNumber}
*/
function one (typeOfValue) {
// TODO: this is a workaround to prevent the following BigNumber conversion error from throwing:
// "TypeError: Cannot implicitly convert a number with >15 significant digits to BigNumber"
// see https://github.com/josdejong/mathjs/issues/3450
// https://github.com/josdejong/mathjs/pull/3375
const convert = Unit._getNumberConverter(typeOf(typeOfValue))
return convert(1)
}
/**
* 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 () {
const ret = this.clone()
if (ret.value !== null) {
if (ret._isDerived() || ret.units.length === 0 || ret.units[0].unit.offset === 0) {
ret.value = abs(ret.value)
} else {
// To give the correct, but unexpected, results for units with an offset.
// For example, abs(-283.15 degC) = -263.15 degC !!!
// We must take the offset into consideration here
const convert = ret._numberConverter() // convert to Fraction or BigNumber if needed
const unitValue = convert(ret.units[0].unit.value)
const nominalOffset = convert(ret.units[0].unit.offset)
const unitOffset = multiplyScalar(unitValue, nominalOffset)
ret.value = subtractScalar(abs(addScalar(ret.value, unitOffset)), unitOffset)
}
}
for (const 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) {
const value = this.value === null ? this._normalize(1) : this.value
let other
if (typeof valuelessUnit === 'string') {
other = Unit.parse(valuelessUnit)
} else if (isUnit(valuelessUnit)) {
other = valuelessUnit.clone()
} else {
throw new Error('String or Unit expected as parameter')
}
if (!this.equalBase(other)) {
throw new Error(`Units do not match ('${other.toString()}' != '${this.toString()}')`)
}
if (other.value !== null) {
throw new Error('Cannot convert to a unit with a value')
}
if (this.value === null || this._isDerived() ||
this.units.length === 0 || other.units.length === 0 ||
this.units[0].unit.offset === other.units[0].unit.offset) {
other.value = clone(value)
} else {
/* Need to adjust value by difference in offset to convert */
const convert = Unit._getNumberConverter(typeOf(value)) // convert to Fraction or BigNumber if needed
const thisUnitValue = this.units[0].unit.value
const thisNominalOffset = this.units[0].unit.offset
const thisUnitOffset = multiplyScalar(thisUnitValue, thisNominalOffset)
const otherUnitValue = other.units[0].unit.value
const otherNominalOffset = other.units[0].unit.offset
const otherUnitOffset = multiplyScalar(otherUnitValue, otherNominalOffset)
other.value = addScalar(value, convert(subtractScalar(thisUnitOffset, otherUnitOffset)))
}
other.fixPrefix = true
other.skipAutomaticSimplification = true
return other
}
/**
* 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) {
let other
if (valuelessUnit) {
// Allow getting the numeric value without converting to a different unit
other = this.to(valuelessUnit)
} else {
other = this.clone()
}
if (other._isDerived() || other.units.length === 0) {
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, "skipSimp": true}`
*/
Unit.prototype.toJSON = function () {
return {
mathjs: 'Unit',
value: this._denormalize(this.value),
unit: this.units.length > 0 ? this.formatUnits() : null,
fixPrefix: this.fixPrefix,
skipSimp: this.skipAutomaticSimplification
}
}
/**
* 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) {
const unit = new Unit(json.value, json.unit ?? undefined)
unit.fixPrefix = json.fixPrefix ?? fixPrefixDefault
unit.skipAutomaticSimplification = json.skipSimp ?? skipAutomaticSimplificationDefault
return unit
}
/**
* Returns the string representation of the unit.
* @memberof Unit
* @return {string}
*/
Unit.prototype.valueOf = Unit.prototype.toString
/**
* Simplify this Unit's unit list and return a new Unit with the simplified list.
* The returned Unit will contain a list of the "best" units for formatting.
*/
Unit.prototype.simplify = function () {
const ret = this.clone()
const proposedUnitList = []
// Search for a matching base
let matchingBase
for (const key in currentUnitSystem) {
if (hasOwnProperty(currentUnitSystem, key)) {
if (ret.hasBase(BASE_UNITS[key])) {
matchingBase = key
break
}
}
}
if (matchingBase === 'NONE') {
ret.units = []
} else {
let matchingUnit
if (matchingBase) {
// Does the unit system have a matching unit?
if (hasOwnProperty(currentUnitSystem, matchingBase)) {
matchingUnit = currentUnitSystem[matchingBase]
}
}
if (matchingUnit) {
ret.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
let missingBaseDim = false
for (let i = 0; i < BASE_DIMENSIONS.length; i++) {
const baseDim = BASE_DIMENSIONS[i]
if (Math.abs(ret.dimensions[i] || 0) > 1e-12) {
if (hasOwnProperty(currentUnitSystem, baseDim)) {
proposedUnitList.push({
unit: currentUnitSystem[baseDim].unit,
prefix: currentUnitSystem[baseDim].prefix,