@danielsimonjr/mathts-core 0.1.1 → 0.1.3

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.
package/README.md CHANGED
@@ -11,17 +11,19 @@ npm install @danielsimonjr/mathts-core
11
11
  ## Usage
12
12
 
13
13
  ```typescript
14
- import { createConfig, isNumeric, isMatrix, VERSION } from '@danielsimonjr/mathts-core';
14
+ import { DEFAULT_CONFIG, isNumber, isMatrix, VERSION } from '@danielsimonjr/mathts-core';
15
15
 
16
- // Create custom configuration
17
- const config = createConfig({
18
- backend: 'wasm',
19
- autoBackend: true,
20
- });
16
+ // Default configuration
17
+ const config = { ...DEFAULT_CONFIG, backend: 'wasm' };
21
18
 
22
19
  // Type guards
23
- console.log(isNumeric(42)); // true
24
- console.log(isMatrix([[1, 2], [3, 4]])); // true
20
+ console.log(isNumber(42)); // true
21
+ console.log(
22
+ isMatrix([
23
+ [1, 2],
24
+ [3, 4],
25
+ ])
26
+ ); // true
25
27
  ```
26
28
 
27
29
  ## API
@@ -34,8 +36,8 @@ console.log(isMatrix([[1, 2], [3, 4]])); // true
34
36
 
35
37
  ### Functions
36
38
 
37
- - `createConfig(overrides?)` - Create configuration with defaults
38
- - `isNumeric(value)` - Type guard for numbers
39
+ - `DEFAULT_CONFIG` - Default configuration object
40
+ - `isNumber(value)` - Type guard for numbers
39
41
  - `isComplex(value)` - Type guard for complex numbers
40
42
  - `isMatrix(value)` - Type guard for matrices
41
43
 
package/dist/index.d.ts CHANGED
@@ -655,6 +655,12 @@ type RoundingMode = 'up' | 'down' | 'ceil' | 'floor' | 'halfUp' | 'halfDown' | '
655
655
  */
656
656
  declare class BigNumber implements MathTSValue {
657
657
  readonly type = "BigNumber";
658
+ /**
659
+ * Duck-typing marker for Decimal.js / mathjs formatter compatibility.
660
+ * Allows external code that checks `obj.isBigNumber === true` to identify
661
+ * this class without an `instanceof` check.
662
+ */
663
+ readonly isBigNumber = true;
658
664
  private readonly _sign;
659
665
  private readonly _coefficient;
660
666
  private readonly _exponent;
@@ -694,13 +700,25 @@ declare class BigNumber implements MathTSValue {
694
700
  static compare(a: BigNumber, b: BigNumber): number;
695
701
  private static compareMagnitude;
696
702
  valueOf(): number;
703
+ /**
704
+ * Convert to a JS number.
705
+ * Alias for `valueOf()` — provided for Decimal.js / mathjs formatter
706
+ * duck-typing compatibility.
707
+ */
708
+ toNumber(): number;
697
709
  toString(): string;
698
710
  toJSON(): {
699
711
  mathjs: string;
700
712
  value: string;
701
713
  };
702
714
  /**
703
- * Convert to fixed-point notation
715
+ * Convert to fixed-point notation.
716
+ *
717
+ * When called with no argument (or `undefined`) returns the full fixed-point
718
+ * string representation without rounding — matching Decimal.js semantics where
719
+ * `toFixed()` is equivalent to a lossless fixed-point stringify.
720
+ * When called with a non-negative integer `decimalPlaces`, rounds and formats
721
+ * to exactly that many digits after the decimal point.
704
722
  */
705
723
  toFixed(decimalPlaces?: number): string;
706
724
  private toFixedInternal;
@@ -724,10 +742,18 @@ declare class BigNumber implements MathTSValue {
724
742
  * Subtraction
725
743
  */
726
744
  subtract(other: Scalar | BigNumber | number | string): BigNumber;
745
+ /**
746
+ * Alias for subtract — mathjs / Decimal.js compatibility.
747
+ */
748
+ sub(other: Scalar | BigNumber | number | string): BigNumber;
727
749
  /**
728
750
  * Multiplication
729
751
  */
730
752
  multiply(other: Scalar | BigNumber | number | string): BigNumber;
753
+ /**
754
+ * Alias for multiply — mathjs / Decimal.js compatibility.
755
+ */
756
+ mul(other: Scalar | BigNumber | number | string): BigNumber;
731
757
  /**
732
758
  * Division
733
759
  */
@@ -755,6 +781,12 @@ declare class BigNumber implements MathTSValue {
755
781
  greaterThanOrEqual(other: BigNumber): boolean;
756
782
  compareTo(other: BigNumber): number;
757
783
  compare(other: BigNumber): number;
784
+ /**
785
+ * Returns true iff this > other.
786
+ * Accepts the same argument types as `add`/`multiply` (BigNumber, number, or string).
787
+ * Named `gt` for Decimal.js / mathjs formatter compatibility.
788
+ */
789
+ gt(other: BigNumber | number | string): boolean;
758
790
  /**
759
791
  * Round to specified decimal places
760
792
  */
@@ -767,6 +799,29 @@ declare class BigNumber implements MathTSValue {
767
799
  floor(): BigNumber;
768
800
  ceil(): BigNumber;
769
801
  trunc(): BigNumber;
802
+ /**
803
+ * Round to `n` significant decimal digits and return a new BigNumber.
804
+ * Delegates to `roundToPrecision`, using the global rounding mode unless
805
+ * an explicit `roundingMode` is supplied.
806
+ *
807
+ * Named `toSignificantDigits` for Decimal.js / mathjs formatter compatibility.
808
+ * When `n` is undefined the value is returned unchanged (no rounding).
809
+ */
810
+ toSignificantDigits(n?: number, roundingMode?: RoundingMode): BigNumber;
811
+ /**
812
+ * The decimal exponent of this number: `floor(log10(|x|))`.
813
+ *
814
+ * Matches Decimal.js semantics:
815
+ * - `12345` → `4` (5 digits → the most-significant place is 10^4)
816
+ * - `0.0123` → `-2` (first significant digit is at 10^-2)
817
+ * - `100` → `2`
818
+ * - `0.01` → `-2`
819
+ * - `0` → `0` (by convention; `isZero()` can be used to distinguish)
820
+ *
821
+ * For special values (NaN, ±Infinity) returns 0 — callers check
822
+ * `isFinite()` / `isNaN()` before using `.e`.
823
+ */
824
+ get e(): number;
770
825
  /**
771
826
  * Modulo (remainder after division)
772
827
  * Result has the same sign as the dividend (this).
@@ -906,6 +961,285 @@ declare const BIGNUMBER_E: BigNumber;
906
961
  declare const BIGNUMBER_LN2: BigNumber;
907
962
  declare const BIGNUMBER_LN10: BigNumber;
908
963
 
964
+ /**
965
+ * Unit definitions for the Unit type.
966
+ *
967
+ * The seven SI base units, plus common derived and imperial units. Each
968
+ * definition stores its multiplicative factor (to base SI) and dimensional
969
+ * exponents. Temperatures carry an additive offset for the K↔°C↔°F
970
+ * conversions.
971
+ *
972
+ * @module @danielsimonjr/mathts-core/types/unit-definitions
973
+ */
974
+ /**
975
+ * The seven SI base dimensions, expressed as a vector of (possibly fractional)
976
+ * exponents.
977
+ */
978
+ interface Dimensions {
979
+ /** Length, base unit metre */
980
+ length: number;
981
+ /** Mass, base unit kilogram */
982
+ mass: number;
983
+ /** Time, base unit second */
984
+ time: number;
985
+ /** Electric current, base unit ampere */
986
+ current: number;
987
+ /** Thermodynamic temperature, base unit kelvin */
988
+ temperature: number;
989
+ /** Amount of substance, base unit mole */
990
+ amount: number;
991
+ /** Luminous intensity, base unit candela */
992
+ luminosity: number;
993
+ }
994
+ /**
995
+ * The zero-dimensional vector (a dimensionless quantity).
996
+ */
997
+ declare const DIMENSIONLESS: Dimensions;
998
+ /**
999
+ * Construct a Dimensions record from a partial spec.
1000
+ *
1001
+ * Missing fields default to 0, so `dim({ length: 1 })` returns the dimension
1002
+ * vector for length.
1003
+ */
1004
+ declare function dim(partial: Partial<Dimensions>): Dimensions;
1005
+ /**
1006
+ * Definition of a single named unit.
1007
+ */
1008
+ interface UnitDef {
1009
+ /** Multiplicative factor: value-in-base = input * multiplier (+ offset). */
1010
+ multiplier: number;
1011
+ /** Additive offset, used for non-multiplicative units like °C and °F. */
1012
+ offset?: number;
1013
+ /** Dimensional signature. */
1014
+ dimensions: Dimensions;
1015
+ /** Whether SI prefixes (k, M, µ, …) may be applied to this notation. */
1016
+ prefixable?: boolean;
1017
+ }
1018
+ /**
1019
+ * The seven SI base units.
1020
+ */
1021
+ declare const BASE_UNITS: Record<string, UnitDef>;
1022
+ /**
1023
+ * Common derived units (SI named units, imperial units, and convenience units).
1024
+ *
1025
+ * This is *not* exhaustive — it covers the most common ~40 units needed for
1026
+ * dimensional-analysis tests. Add more as needed by downstream callers.
1027
+ */
1028
+ declare const DERIVED_UNITS: Record<string, UnitDef>;
1029
+ /**
1030
+ * Combined registry — both base and derived units in one map.
1031
+ */
1032
+ declare const ALL_UNITS: Record<string, UnitDef>;
1033
+ /**
1034
+ * Convenience aliases mapping common Unicode/ASCII variants to the canonical
1035
+ * notation key. Used by the parser; not part of the registered notation set.
1036
+ */
1037
+ declare const UNIT_ALIASES: Record<string, string>;
1038
+ /**
1039
+ * Lookup an exact (non-prefixed) unit definition.
1040
+ */
1041
+ declare function getUnitDef(name: string): UnitDef | undefined;
1042
+
1043
+ /**
1044
+ * Unit type — dimensional analysis, composition, conversion, and pretty-print.
1045
+ *
1046
+ * A {@link Unit} couples a numeric magnitude to a dimensional signature derived
1047
+ * from a registry of named units (see {@link ./unit-definitions}). Units are
1048
+ * **immutable**: every operation returns a new instance. The canonical
1049
+ * representation always stores the value in SI base units, regardless of how
1050
+ * the unit was constructed — so `new Unit(5, 'km').value === 5000` (metres).
1051
+ * The original notation is preserved on the instance for round-trip display.
1052
+ *
1053
+ * Design notes (intentional differences from mathjs's `Unit` class):
1054
+ * - **Immutable value semantics** instead of mutable JS prototype-class style.
1055
+ * - **No closure over a `math` instance.** Unit is self-contained — no
1056
+ * dependency on `addScalar`, `format`, `BigNumber`, etc. Values are plain
1057
+ * JS numbers.
1058
+ * - **`dimensions` is a struct** (a record over the seven SI bases) rather
1059
+ * than mathjs's array indexed by `BASE_DIMENSIONS`. Cheaper to work with in
1060
+ * TS, and lets the field be `Readonly<Dimensions>`.
1061
+ * - **Temperature offsets are honoured only for single-temperature-degree
1062
+ * units** (e.g. `°C` alone, not `°C/s`), matching mathjs but stated
1063
+ * explicitly here.
1064
+ *
1065
+ * @module @danielsimonjr/mathts-core/types/unit
1066
+ */
1067
+
1068
+ /**
1069
+ * Thrown when a unit operation requires matching dimensions but the operands
1070
+ * disagree. Carries the offending dimension vectors for debugging.
1071
+ */
1072
+ declare class DimensionMismatchError extends Error {
1073
+ readonly left: Dimensions;
1074
+ readonly right: Dimensions;
1075
+ readonly name = "DimensionMismatchError";
1076
+ constructor(left: Dimensions, right: Dimensions, op: string);
1077
+ }
1078
+ /** Thrown when a notation string cannot be parsed against the registry. */
1079
+ declare class UnitParseError extends Error {
1080
+ readonly name = "UnitParseError";
1081
+ constructor(notation: string, reason: string);
1082
+ }
1083
+ /**
1084
+ * A physical quantity: a numeric magnitude paired with a dimensional
1085
+ * signature derived from named units.
1086
+ *
1087
+ * Construction examples:
1088
+ * ```ts
1089
+ * new Unit(5, 'm'); // 5 metres
1090
+ * new Unit(3.5, 'km/h'); // 3.5 km/h
1091
+ * new Unit(20, '°C'); // 20 °C
1092
+ * new Unit(1, 'kg·m/s²'); // 1 newton (composed)
1093
+ * ```
1094
+ *
1095
+ * All instances are immutable; every operation returns a new {@link Unit}.
1096
+ * The `value` field is always in SI base units, so:
1097
+ *
1098
+ * ```ts
1099
+ * new Unit(5, 'km').value; // 5000 (canonical metres)
1100
+ * new Unit(20, '°C').value; // 293.15 (canonical kelvin)
1101
+ * ```
1102
+ */
1103
+ declare class Unit {
1104
+ /** Discriminator (matches the prototype-flag convention). */
1105
+ readonly type = "Unit";
1106
+ /** Used by `isUnit()` and typed-function dispatch. */
1107
+ readonly isUnit = true;
1108
+ /** Numeric magnitude in **SI base units**. */
1109
+ readonly value: number;
1110
+ /** Dimensional signature. */
1111
+ readonly dimensions: Readonly<Dimensions>;
1112
+ /** Original notation string, preserved for `toString()` round-trip. */
1113
+ readonly notation: string;
1114
+ /**
1115
+ * Construct a Unit from a numeric value and a notation string.
1116
+ *
1117
+ * The notation is parsed against the registered unit definitions in
1118
+ * {@link ./unit-definitions}. SI prefixes are applied automatically when
1119
+ * the bare notation doesn't match a registered unit. Compound expressions
1120
+ * like `"m/s²"`, `"kg·m/s²"`, and `"1/s"` are supported.
1121
+ *
1122
+ * @throws {UnitParseError} if `notation` cannot be parsed against the
1123
+ * registered unit definitions.
1124
+ */
1125
+ constructor(value: number, notation: string);
1126
+ /**
1127
+ * Internal construction shortcut from already-canonical fields. **Not
1128
+ * intended for direct use** — most callers should use the `(value,
1129
+ * notation)` form.
1130
+ */
1131
+ constructor(value: number, dimensions: Readonly<Dimensions>, notation: string);
1132
+ /**
1133
+ * Add two units. Requires identical dimensions.
1134
+ *
1135
+ * @throws {DimensionMismatchError} if dimensions differ.
1136
+ */
1137
+ add(other: Unit): Unit;
1138
+ /**
1139
+ * Subtract two units. Requires identical dimensions.
1140
+ *
1141
+ * @throws {DimensionMismatchError} if dimensions differ.
1142
+ */
1143
+ sub(other: Unit): Unit;
1144
+ /**
1145
+ * Multiply by another unit or a scalar. Dimensions add when multiplying by
1146
+ * another unit; unchanged when multiplying by a scalar.
1147
+ */
1148
+ mul(other: Unit | number): Unit;
1149
+ /**
1150
+ * Divide by another unit or a scalar. Dimensions subtract when dividing by
1151
+ * another unit; unchanged when dividing by a scalar.
1152
+ */
1153
+ div(other: Unit | number): Unit;
1154
+ /**
1155
+ * Raise to an integer or rational power. Dimensions scale by `n`.
1156
+ */
1157
+ pow(n: number): Unit;
1158
+ /**
1159
+ * Convert to a target unit. Dimensions must match.
1160
+ *
1161
+ * @throws {DimensionMismatchError} if `targetNotation`'s dimensions differ
1162
+ * from this unit's.
1163
+ */
1164
+ to(targetNotation: string): Unit;
1165
+ /**
1166
+ * Pick a unit (with SI prefix) that gives a magnitude closest to 1.
1167
+ *
1168
+ * Searches the unit registry for entries matching this unit's dimensions,
1169
+ * then applies each SI prefix in {@link BEST_PREFIXES} to find the
1170
+ * representation minimising `|log10(displayed value)|`.
1171
+ *
1172
+ * If no registered unit matches the dimensions, falls back to a synthetic
1173
+ * notation describing the dimensional vector.
1174
+ */
1175
+ toBest(): Unit;
1176
+ /** True iff dimensions and canonical value are equal. */
1177
+ equals(other: Unit): boolean;
1178
+ /** True iff dimensions match (values may differ). */
1179
+ dimensionsEqual(other: Unit): boolean;
1180
+ /**
1181
+ * Pretty-print. If `notation` is set (the common case), display the value
1182
+ * in that notation — otherwise emit a dimensional signature.
1183
+ */
1184
+ toString(): string;
1185
+ /** JSON-serialisable record. */
1186
+ toJSON(): {
1187
+ mathts: 'Unit';
1188
+ value: number;
1189
+ notation: string;
1190
+ };
1191
+ /**
1192
+ * Rehydrate from a JSON record produced by {@link toJSON}.
1193
+ *
1194
+ * @throws {UnitParseError} if `json.notation` cannot be parsed.
1195
+ */
1196
+ static fromJSON(json: {
1197
+ value: number;
1198
+ notation: string;
1199
+ }): Unit;
1200
+ /**
1201
+ * Parse a full unit expression (with optional leading numeric coefficient).
1202
+ *
1203
+ * Example: `Unit.parse('5 km/h')`.
1204
+ */
1205
+ static parse(input: string): Unit;
1206
+ }
1207
+
1208
+ /**
1209
+ * Duck-typing guard for {@link Unit}. Mirrors the convention used by
1210
+ * {@link Complex}, {@link Fraction}, and {@link BigNumber}.
1211
+ */
1212
+ declare function isUnit$1(value: unknown): value is Unit;
1213
+
1214
+ /**
1215
+ * SI prefixes for the Unit type.
1216
+ *
1217
+ * Maps single- and double-letter prefixes to their multiplicative factor in
1218
+ * base units. The full SI prefix range (from y = 1e-24 to Y = 1e24) is
1219
+ * supported, plus the binary prefixes used for digital information units.
1220
+ *
1221
+ * @module @danielsimonjr/mathts-core/types/unit-prefixes
1222
+ */
1223
+ /**
1224
+ * Standard SI prefixes (mass/length/energy/etc.).
1225
+ *
1226
+ * Note the ambiguity-resolution priority: longer prefixes (e.g. `da`)
1227
+ * must be tried before single-letter ones (`d`, `a`) in parsers.
1228
+ */
1229
+ declare const SI_PREFIXES: Record<string, number>;
1230
+ /**
1231
+ * Set of "good" prefixes to use in `toBest()` selection.
1232
+ *
1233
+ * Excludes `h`, `da`, `d`, `c` (commonly only used for centimeters and similar
1234
+ * legacy notations); using these in `toBest()` would produce awkward outputs
1235
+ * like "0.4 hg" instead of "40 g".
1236
+ */
1237
+ declare const BEST_PREFIXES: ReadonlyArray<string>;
1238
+ /**
1239
+ * Look up an SI prefix multiplier. Returns `undefined` if not a known prefix.
1240
+ */
1241
+ declare function getPrefix(name: string): number | undefined;
1242
+
909
1243
  /**
910
1244
  * MathTS typed-function Integration
911
1245
  *
@@ -975,6 +1309,10 @@ declare const isDenseMatrix: (x: unknown) => boolean;
975
1309
  declare const isSparseMatrix: (x: unknown) => boolean;
976
1310
  /**
977
1311
  * Check if value is a Unit
1312
+ *
1313
+ * Recognises both the native {@link Unit} class (which exposes `value`,
1314
+ * `dimensions`, and `notation`) and the legacy duck-typed shape used by
1315
+ * mathjs-compatibility shims (`{ value, unit, type }`).
978
1316
  */
979
1317
  declare const isUnit: (x: unknown) => boolean;
980
1318
  /**
@@ -1233,4 +1571,4 @@ declare const math: {
1233
1571
 
1234
1572
  declare const VERSION = "0.1.0";
1235
1573
 
1236
- export { BIGNUMBER_E, BIGNUMBER_LN10, BIGNUMBER_LN2, BIGNUMBER_NEG_ONE, BIGNUMBER_ONE, BIGNUMBER_PI, BIGNUMBER_TEN, BIGNUMBER_ZERO, type BackendType, BigNumber, type BigNumberConfig, COMPLEX_NEG_ONE, COMPLEX_ONE, COMPLEX_ZERO, Complex, type ConversionDef, DEFAULT_CONFIG, FRACTION_HALF, FRACTION_NEG_ONE, FRACTION_ONE, FRACTION_QUARTER, FRACTION_THIRD, FRACTION_ZERO, type FactoryDependencies, type FactoryFunction, type FactoryImport, Fraction, FunctionRegistry, I, type IBigNumber, type IComplex, type IFraction, type IMatrix, MATHTS_CONVERSIONS, MATHTS_TYPES, type MathTSConfig, type MathTSValue, type MatrixBackend, type MatrixDimensions, type NumericType, type RoundingMode, type Scalar, type TypeDef, TypeRegistry, VERSION, createFactory, createMathTSTyped, createTypedFunction, initTypedWasm, isArray, isBigInt, isBigNumber, isBoolean, isComplex, isDenseMatrix, isFraction, isFunction, isMatrix, isNull, isNumber, isObject, isSparseMatrix, isString, isTypedWasmAvailable, isUndefined, isUnit, math, mathTyped, registerNativeTypes, registry };
1574
+ export { ALL_UNITS, BASE_UNITS, BEST_PREFIXES, BIGNUMBER_E, BIGNUMBER_LN10, BIGNUMBER_LN2, BIGNUMBER_NEG_ONE, BIGNUMBER_ONE, BIGNUMBER_PI, BIGNUMBER_TEN, BIGNUMBER_ZERO, type BackendType, BigNumber, type BigNumberConfig, COMPLEX_NEG_ONE, COMPLEX_ONE, COMPLEX_ZERO, Complex, type ConversionDef, DEFAULT_CONFIG, DERIVED_UNITS, DIMENSIONLESS, DimensionMismatchError, type Dimensions, FRACTION_HALF, FRACTION_NEG_ONE, FRACTION_ONE, FRACTION_QUARTER, FRACTION_THIRD, FRACTION_ZERO, type FactoryDependencies, type FactoryFunction, type FactoryImport, Fraction, FunctionRegistry, I, type IBigNumber, type IComplex, type IFraction, type IMatrix, MATHTS_CONVERSIONS, MATHTS_TYPES, type MathTSConfig, type MathTSValue, type MatrixBackend, type MatrixDimensions, type NumericType, type RoundingMode, SI_PREFIXES, type Scalar, type TypeDef, TypeRegistry, UNIT_ALIASES, Unit, type UnitDef, UnitParseError, VERSION, createFactory, createMathTSTyped, createTypedFunction, dim, getPrefix, getUnitDef, initTypedWasm, isArray, isBigInt, isBigNumber, isBoolean, isComplex, isDenseMatrix, isFraction, isFunction, isMatrix, isNull, isNumber, isObject, isSparseMatrix, isString, isTypedWasmAvailable, isUndefined, isUnit, isUnit$1 as isUnitValue, math, mathTyped, registerNativeTypes, registry };