mathjs 14.5.3 → 14.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (31) hide show
  1. package/HISTORY.md +9 -1
  2. package/lib/browser/math.js +1 -1
  3. package/lib/browser/math.js.LICENSE.txt +2 -2
  4. package/lib/browser/math.js.map +1 -1
  5. package/lib/cjs/entry/dependenciesAny/dependenciesToBest.generated.js +17 -0
  6. package/lib/cjs/entry/dependenciesAny/dependenciesUnitClass.generated.js +2 -0
  7. package/lib/cjs/entry/dependenciesAny.generated.js +7 -0
  8. package/lib/cjs/entry/impureFunctionsAny.generated.js +1 -0
  9. package/lib/cjs/entry/pureFunctionsAny.generated.js +7 -3
  10. package/lib/cjs/expression/embeddedDocs/embeddedDocs.js +2 -0
  11. package/lib/cjs/expression/embeddedDocs/function/units/toBest.js +14 -0
  12. package/lib/cjs/factoriesAny.js +7 -0
  13. package/lib/cjs/function/arithmetic/sign.js +1 -1
  14. package/lib/cjs/function/unit/toBest.js +53 -0
  15. package/lib/cjs/header.js +2 -2
  16. package/lib/cjs/type/unit/Unit.js +106 -19
  17. package/lib/cjs/version.js +1 -1
  18. package/lib/esm/entry/dependenciesAny/dependenciesToBest.generated.js +10 -0
  19. package/lib/esm/entry/dependenciesAny/dependenciesUnitClass.generated.js +2 -0
  20. package/lib/esm/entry/dependenciesAny.generated.js +1 -0
  21. package/lib/esm/entry/impureFunctionsAny.generated.js +2 -1
  22. package/lib/esm/entry/pureFunctionsAny.generated.js +6 -2
  23. package/lib/esm/expression/embeddedDocs/embeddedDocs.js +2 -0
  24. package/lib/esm/expression/embeddedDocs/function/units/toBest.js +8 -0
  25. package/lib/esm/factoriesAny.js +1 -0
  26. package/lib/esm/function/arithmetic/sign.js +1 -1
  27. package/lib/esm/function/unit/toBest.js +47 -0
  28. package/lib/esm/type/unit/Unit.js +106 -19
  29. package/lib/esm/version.js +1 -1
  30. package/package.json +7 -7
  31. package/types/index.d.ts +31 -0
@@ -0,0 +1,47 @@
1
+ import { factory } from '../../utils/factory.js';
2
+ var name = 'toBest';
3
+ var dependencies = ['typed'];
4
+ export var createToBest = /* #__PURE__ */factory(name, dependencies, _ref => {
5
+ var {
6
+ typed
7
+ } = _ref;
8
+ /**
9
+ * Converts a unit to the most appropriate display unit.
10
+ * When no preferred units are provided, the function automatically find the best prefix.
11
+ * When preferred units are provided, it converts to
12
+ * the unit that gives a value closest to 1.
13
+ *
14
+ * Syntax:
15
+ *
16
+ * math.toBest(unit)
17
+ * math.toBest(unit, unitList)
18
+ * math.toBest(unit, unitList, options)
19
+ *
20
+ * Where:
21
+ * - `unitList` is an optional array of preferred target units as string or Unit.
22
+ * - `options` is an optional object with options, formed as follows:
23
+ * - `offset`: number | BigNumber
24
+ *
25
+ * Examples:
26
+ *
27
+ * math.unit(0.05, 'm').toBest(['cm', 'mm']) // returns Unit 5 cm
28
+ * math.unit(2 / 3, 'cm').toBest() // returns Unit 0.6666666666666666 cm
29
+ * math.unit(10, 'm').toBest(['mm', 'km'], { offset: 1.5 }) // returns Unit 10000 mm
30
+ *
31
+ * See also:
32
+ *
33
+ * unit, to, format
34
+ *
35
+ * @param {Unit} x The unit to be converted
36
+ * @param {Array<string>} [unitList=[]] Optional array of preferred target units
37
+ * @param {Object} [options] Optional options object
38
+ * @return {Unit} Value converted to the best matching unit
39
+ */
40
+ return typed(name, {
41
+ Unit: x => x.toBest(),
42
+ 'Unit, string': (x, unitList) => x.toBest(unitList.split(',')),
43
+ 'Unit, string, Object': (x, unitList, options) => x.toBest(unitList.split(','), options),
44
+ 'Unit, Array': (x, unitList) => x.toBest(unitList),
45
+ 'Unit, Array, Object': (x, unitList, options) => x.toBest(unitList, options)
46
+ });
47
+ });
@@ -9,7 +9,7 @@ import { endsWith } from '../../utils/string.js';
9
9
  import { clone, hasOwnProperty } from '../../utils/object.js';
10
10
  import { createBigNumberPi as createPi } from '../../utils/bignumber/constants.js';
11
11
  var name = 'Unit';
12
- var dependencies = ['?on', 'config', 'addScalar', 'subtractScalar', 'multiplyScalar', 'divideScalar', 'pow', 'abs', 'fix', 'round', 'equal', 'isNumeric', 'format', 'number', 'Complex', 'BigNumber', 'Fraction'];
12
+ var dependencies = ['?on', 'config', 'addScalar', 'subtractScalar', 'multiplyScalar', 'divideScalar', 'pow', 'abs', 'fix', 'round', 'equal', 'isNumeric', 'format', 'toBest', 'number', 'Complex', 'BigNumber', 'Fraction'];
13
13
  export var createUnitClass = /* #__PURE__ */factory(name, dependencies, _ref => {
14
14
  var {
15
15
  on,
@@ -25,6 +25,7 @@ export var createUnitClass = /* #__PURE__ */factory(name, dependencies, _ref =>
25
25
  equal,
26
26
  isNumeric,
27
27
  format,
28
+ toBest,
28
29
  number: _number,
29
30
  Complex,
30
31
  BigNumber: _BigNumber,
@@ -1041,6 +1042,54 @@ export var createUnitClass = /* #__PURE__ */factory(name, dependencies, _ref =>
1041
1042
  return str;
1042
1043
  };
1043
1044
 
1045
+ /**
1046
+ * Get a unit, with optional formatting options.
1047
+ * @memberof Unit
1048
+ * @param {string[] | Unit[]} [units] Array of units strings or valueLess Unit objects in wich choose the best one
1049
+ * @param {Object} [options] Options for parsing the unit. See parseUnit for details.
1050
+ *
1051
+ * @return {Unit} Returns a new Unit with the given value and unit.
1052
+ */
1053
+ Unit.prototype.toBest = function () {
1054
+ var unitList = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : [];
1055
+ var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
1056
+ if (unitList && !Array.isArray(unitList)) {
1057
+ throw new Error('Invalid unit type. Expected string or Unit.');
1058
+ }
1059
+ var startPrefixes = this.units[0].unit.prefixes;
1060
+ if (unitList && unitList.length > 0) {
1061
+ var unitObjects = unitList.map(u => {
1062
+ var unit = null;
1063
+ if (typeof u === 'string') {
1064
+ unit = Unit.parse(u);
1065
+ if (!unit) {
1066
+ throw new Error('Invalid unit type. Expected compatible string or Unit.');
1067
+ }
1068
+ } else if (!isUnit(u)) {
1069
+ throw new Error('Invalid unit type. Expected compatible string or Unit.');
1070
+ }
1071
+ if (unit === null) {
1072
+ unit = u.clone();
1073
+ }
1074
+ try {
1075
+ this.to(unit.formatUnits());
1076
+ return unit;
1077
+ } catch (e) {
1078
+ throw new Error('Invalid unit type. Expected compatible string or Unit.');
1079
+ }
1080
+ });
1081
+ var prefixes = unitObjects.map(el => el.units[0].prefix);
1082
+ this.units[0].unit.prefixes = prefixes.reduce((acc, prefix) => {
1083
+ acc[prefix.name] = prefix;
1084
+ return acc;
1085
+ }, {});
1086
+ this.units[0].prefix = prefixes[0];
1087
+ }
1088
+ var result = formatBest(this, options).simp;
1089
+ this.units[0].unit.prefixes = startPrefixes;
1090
+ result.fixPrefix = true;
1091
+ return result;
1092
+ };
1044
1093
  /**
1045
1094
  * Get a string representation of the Unit, with optional formatting options.
1046
1095
  * @memberof Unit
@@ -1051,11 +1100,54 @@ export var createUnitClass = /* #__PURE__ */factory(name, dependencies, _ref =>
1051
1100
  * @return {string}
1052
1101
  */
1053
1102
  Unit.prototype.format = function (options) {
1103
+ var {
1104
+ simp,
1105
+ valueStr,
1106
+ unitStr
1107
+ } = formatBest(this, options);
1108
+ var str = valueStr;
1109
+ if (simp.value && isComplex(simp.value)) {
1110
+ str = '(' + str + ')'; // Surround complex values with ( ) to enable better parsing
1111
+ }
1112
+ if (unitStr.length > 0 && str.length > 0) {
1113
+ str += ' ';
1114
+ }
1115
+ str += unitStr;
1116
+ return str;
1117
+ };
1118
+
1119
+ /**
1120
+ * Helper function to normalize a unit for conversion and formatting
1121
+ * @param {Unit} unit The unit to be normalized
1122
+ * @return {Object} Object with normalized unit and value
1123
+ * @private
1124
+ */
1125
+ function formatBest(unit) {
1126
+ var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
1054
1127
  // Simplfy the unit list, unless it is valueless or was created directly in the
1055
1128
  // constructor or as the result of to or toSI
1056
- var simp = this.skipAutomaticSimplification || this.value === null ? this.clone() : this.simplify();
1129
+ var simp = unit.skipAutomaticSimplification || unit.value === null ? unit.clone() : unit.simplify();
1057
1130
 
1058
1131
  // Apply some custom logic for handling VA and VAR. The goal is to express the value of the unit as a real value, if possible. Otherwise, use a real-valued unit instead of a complex-valued one.
1132
+ handleVAandVARUnits(simp);
1133
+ // Now apply the best prefix
1134
+ // Units must have only one unit and not have the fixPrefix flag set
1135
+ applyBestPrefixIfNeeded(simp, options.offset);
1136
+ var value = simp._denormalize(simp.value);
1137
+ var valueStr = simp.value !== null ? format(value, options || {}) : '';
1138
+ var unitStr = simp.formatUnits();
1139
+ return {
1140
+ simp,
1141
+ valueStr,
1142
+ unitStr
1143
+ };
1144
+ }
1145
+
1146
+ /**
1147
+ * Helper to handle VA and VAR units
1148
+ * @param {Unit} simp The unit to be normalized
1149
+ */
1150
+ function handleVAandVARUnits(simp) {
1059
1151
  var isImaginary = false;
1060
1152
  if (typeof simp.value !== 'undefined' && simp.value !== null && isComplex(simp.value)) {
1061
1153
  // TODO: Make this better, for example, use relative magnitude of re and im rather than absolute
@@ -1072,37 +1164,32 @@ export var createUnitClass = /* #__PURE__ */factory(name, dependencies, _ref =>
1072
1164
  }
1073
1165
  }
1074
1166
  }
1167
+ }
1075
1168
 
1076
- // Now apply the best prefix
1077
- // Units must have only one unit and not have the fixPrefix flag set
1169
+ /**
1170
+ * Helper to apply the best prefix if needed
1171
+ * @param {Unit} simp The unit to be normalized
1172
+ */
1173
+ function applyBestPrefixIfNeeded(simp, offset) {
1078
1174
  if (simp.units.length === 1 && !simp.fixPrefix) {
1079
1175
  // Units must have integer powers, otherwise the prefix will change the
1080
1176
  // outputted value by not-an-integer-power-of-ten
1081
1177
  if (Math.abs(simp.units[0].power - Math.round(simp.units[0].power)) < 1e-14) {
1082
1178
  // Apply the best prefix
1083
- simp.units[0].prefix = simp._bestPrefix();
1179
+ simp.units[0].prefix = simp._bestPrefix(offset);
1084
1180
  }
1085
1181
  }
1086
- var value = simp._denormalize(simp.value);
1087
- var str = simp.value !== null ? format(value, options || {}) : '';
1088
- var unitStr = simp.formatUnits();
1089
- if (simp.value && isComplex(simp.value)) {
1090
- str = '(' + str + ')'; // Surround complex values with ( ) to enable better parsing
1091
- }
1092
- if (unitStr.length > 0 && str.length > 0) {
1093
- str += ' ';
1094
- }
1095
- str += unitStr;
1096
- return str;
1097
- };
1182
+ }
1098
1183
 
1099
1184
  /**
1100
1185
  * Calculate the best prefix using current value.
1101
1186
  * @memberof Unit
1102
1187
  * @returns {Object} prefix
1188
+ * @param {number} [offset] Optional offset for the best prefix calculation (default 1.2)
1103
1189
  * @private
1104
1190
  */
1105
1191
  Unit.prototype._bestPrefix = function () {
1192
+ var offset = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 1.2;
1106
1193
  if (this.units.length !== 1) {
1107
1194
  throw new Error('Can only compute the best prefix for single units with integer powers, like kg, s^2, N^-1, and so forth!');
1108
1195
  }
@@ -1125,7 +1212,7 @@ export var createUnitClass = /* #__PURE__ */factory(name, dependencies, _ref =>
1125
1212
  return bestPrefix;
1126
1213
  }
1127
1214
  var power = this.units[0].power;
1128
- var bestDiff = Math.log(absValue / Math.pow(bestPrefix.value * absUnitValue, power)) / Math.LN10 - 1.2;
1215
+ var bestDiff = Math.log(absValue / Math.pow(bestPrefix.value * absUnitValue, power)) / Math.LN10 - offset;
1129
1216
  if (bestDiff > -2.200001 && bestDiff < 1.800001) return bestPrefix; // Allow the original prefix
1130
1217
  bestDiff = Math.abs(bestDiff);
1131
1218
  var prefixes = this.units[0].unit.prefixes;
@@ -1133,7 +1220,7 @@ export var createUnitClass = /* #__PURE__ */factory(name, dependencies, _ref =>
1133
1220
  if (hasOwnProperty(prefixes, p)) {
1134
1221
  var prefix = prefixes[p];
1135
1222
  if (prefix.scientific) {
1136
- var diff = Math.abs(Math.log(absValue / Math.pow(prefix.value * absUnitValue, power)) / Math.LN10 - 1.2);
1223
+ var diff = Math.abs(Math.log(absValue / Math.pow(prefix.value * absUnitValue, power)) / Math.LN10 - offset);
1137
1224
  if (diff < bestDiff || diff === bestDiff && prefix.name.length < bestPrefix.name.length) {
1138
1225
  // choose the prefix with the smallest diff, or if equal, choose the one
1139
1226
  // with the shortest name (can happen with SHORTLONG for example)
@@ -1,3 +1,3 @@
1
- export var version = '14.5.3';
1
+ export var version = '14.6.0';
2
2
  // Note: This file is automatically generated when building math.js.
3
3
  // Changes made in this file will be overwritten.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "mathjs",
3
- "version": "14.5.3",
3
+ "version": "14.6.0",
4
4
  "description": "Math.js is an extensive math library for JavaScript and Node.js. It features a flexible expression parser with support for symbolic computation, comes with a large set of built-in functions and constants, and offers an integrated solution to work with different data types like numbers, big numbers, complex numbers, fractions, units, and matrices.",
5
5
  "author": "Jos de Jong <wjosdejong@gmail.com> (https://github.com/josdejong)",
6
6
  "homepage": "https://mathjs.org",
@@ -44,13 +44,13 @@
44
44
  "@babel/register": "7.27.1",
45
45
  "@types/assert": "1.5.11",
46
46
  "@types/mocha": "10.0.10",
47
- "@typescript-eslint/eslint-plugin": "8.35.1",
48
- "@typescript-eslint/parser": "8.35.1",
47
+ "@typescript-eslint/eslint-plugin": "8.38.0",
48
+ "@typescript-eslint/parser": "8.38.0",
49
49
  "assert": "2.1.0",
50
50
  "babel-loader": "10.0.0",
51
51
  "c8": "10.1.3",
52
52
  "codecov": "3.8.3",
53
- "core-js": "3.43.0",
53
+ "core-js": "3.44.0",
54
54
  "del": "8.0.0",
55
55
  "dtslint": "4.2.1",
56
56
  "eigen": "0.2.2",
@@ -60,9 +60,9 @@
60
60
  "eslint-plugin-import": "2.32.0",
61
61
  "eslint-plugin-mocha": "10.5.0",
62
62
  "eslint-plugin-n": "16.6.2",
63
- "eslint-plugin-prettier": "5.5.1",
63
+ "eslint-plugin-prettier": "5.5.3",
64
64
  "eslint-plugin-promise": "6.6.0",
65
- "expect-type": "1.2.1",
65
+ "expect-type": "1.2.2",
66
66
  "expr-eval": "2.0.2",
67
67
  "fancy-log": "2.0.0",
68
68
  "glob": "11.0.3",
@@ -93,7 +93,7 @@
93
93
  "tinybench": "4.0.1",
94
94
  "ts-node": "10.9.2",
95
95
  "typescript": "5.8.3",
96
- "webpack": "5.99.9",
96
+ "webpack": "5.100.2",
97
97
  "zeros": "1.0.0"
98
98
  },
99
99
  "type": "module",
package/types/index.d.ts CHANGED
@@ -3488,6 +3488,18 @@ export interface MathJsInstance extends MathJsFactory {
3488
3488
  */
3489
3489
  to(x: Unit | MathCollection, unit: Unit | string): Unit | MathCollection
3490
3490
 
3491
+ /**
3492
+ * Converts a unit to the most appropriate display unit.
3493
+ * When no preferred units are provided, the function automatically find the best prefix.
3494
+ * When preferred units are provided, it converts to
3495
+ * the unit that gives a value closest to 1.
3496
+ * @param preferredUnits - Optional preferred target units
3497
+ * @param options - Optional options object
3498
+ * @returns Unit with optimized prefix/unit
3499
+ */
3500
+ toBest(): Unit
3501
+ toBest(units: string[] | Unit[], options: object): Unit
3502
+
3491
3503
  /*************************************************************************
3492
3504
  * Utils
3493
3505
  ************************************************************************/
@@ -3834,6 +3846,7 @@ export const {
3834
3846
  formatDependencies,
3835
3847
  printDependencies,
3836
3848
  toDependencies,
3849
+ toBestDependencies,
3837
3850
  isPrimeDependencies,
3838
3851
  numericDependencies,
3839
3852
  divideScalarDependencies,
@@ -4177,6 +4190,8 @@ export interface Unit {
4177
4190
  pow(unit: Unit): Unit
4178
4191
  abs(unit: Unit): Unit
4179
4192
  to(unit: string | Unit): Unit
4193
+ toBest(): Unit
4194
+ toBest(units?: string[] | Unit[], options?: object): Unit
4180
4195
  toNumber(unit?: string): number
4181
4196
  toNumeric(unit?: string): number | Fraction | BigNumber
4182
4197
  toSI(): Unit
@@ -6991,6 +7006,21 @@ export interface MathJsChain<TValue> {
6991
7006
  unit: Unit | string
6992
7007
  ): MathJsChain<Unit | MathCollection>
6993
7008
 
7009
+ /**
7010
+ * Converts a unit to the most appropriate display unit.
7011
+ * When no preferred units are provided, the function automatically find the best prefix.
7012
+ * When preferred units are provided, it converts to
7013
+ * the unit that gives a value closest to 1.
7014
+ * @param preferredUnits - Optional preferred target units
7015
+ * @param options - Optional options object
7016
+ */
7017
+ toBest(this: MathJsChain<Unit>): MathJsChain<Unit>
7018
+ toBest(
7019
+ this: MathJsChain<Unit>,
7020
+ units: string[] | Unit[],
7021
+ options: object
7022
+ ): MathJsChain<Unit>
7023
+
6994
7024
  /*************************************************************************
6995
7025
  * Utils functions
6996
7026
  ************************************************************************/
@@ -7380,6 +7410,7 @@ export const {
7380
7410
 
7381
7411
  // unit functions
7382
7412
  to,
7413
+ toBest,
7383
7414
 
7384
7415
  // util functions
7385
7416
  isNumber,