@danielsimonjr/mathts-core 0.1.2 → 0.1.4

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;
@@ -716,6 +734,28 @@ declare class BigNumber implements MathTSValue {
716
734
  * Convert to bigint (truncated)
717
735
  */
718
736
  toBigInt(): bigint;
737
+ /**
738
+ * Binary string representation, e.g. `255 -> '0b11111111'`, `0.5 -> '0b0.1'`.
739
+ * Mirrors Decimal.js `toBinary()`. Negatives carry a leading `-`.
740
+ */
741
+ toBinary(): string;
742
+ /**
743
+ * Octal string representation, e.g. `8 -> '0o10'`.
744
+ * Mirrors Decimal.js `toOctal()`.
745
+ */
746
+ toOctal(): string;
747
+ /**
748
+ * Hexadecimal string representation, e.g. `255 -> '0xff'`, `10.5 -> '0xa.8'`.
749
+ * Mirrors Decimal.js `toHexadecimal()`.
750
+ */
751
+ toHexadecimal(): string;
752
+ /**
753
+ * Shared radix formatter for {@link toBinary}/{@link toOctal}/{@link toHexadecimal}.
754
+ * Integers and terminating fractions are exact; a non-terminating fraction is
755
+ * truncated at `maxFractionDigits` radix digits (a safety bound — the common
756
+ * use is integer formatting).
757
+ */
758
+ private toRadixString;
719
759
  /**
720
760
  * Addition
721
761
  */
@@ -724,10 +764,18 @@ declare class BigNumber implements MathTSValue {
724
764
  * Subtraction
725
765
  */
726
766
  subtract(other: Scalar | BigNumber | number | string): BigNumber;
767
+ /**
768
+ * Alias for subtract — mathjs / Decimal.js compatibility.
769
+ */
770
+ sub(other: Scalar | BigNumber | number | string): BigNumber;
727
771
  /**
728
772
  * Multiplication
729
773
  */
730
774
  multiply(other: Scalar | BigNumber | number | string): BigNumber;
775
+ /**
776
+ * Alias for multiply — mathjs / Decimal.js compatibility.
777
+ */
778
+ mul(other: Scalar | BigNumber | number | string): BigNumber;
731
779
  /**
732
780
  * Division
733
781
  */
@@ -755,6 +803,12 @@ declare class BigNumber implements MathTSValue {
755
803
  greaterThanOrEqual(other: BigNumber): boolean;
756
804
  compareTo(other: BigNumber): number;
757
805
  compare(other: BigNumber): number;
806
+ /**
807
+ * Returns true iff this > other.
808
+ * Accepts the same argument types as `add`/`multiply` (BigNumber, number, or string).
809
+ * Named `gt` for Decimal.js / mathjs formatter compatibility.
810
+ */
811
+ gt(other: BigNumber | number | string): boolean;
758
812
  /**
759
813
  * Round to specified decimal places
760
814
  */
@@ -767,6 +821,29 @@ declare class BigNumber implements MathTSValue {
767
821
  floor(): BigNumber;
768
822
  ceil(): BigNumber;
769
823
  trunc(): BigNumber;
824
+ /**
825
+ * Round to `n` significant decimal digits and return a new BigNumber.
826
+ * Delegates to `roundToPrecision`, using the global rounding mode unless
827
+ * an explicit `roundingMode` is supplied.
828
+ *
829
+ * Named `toSignificantDigits` for Decimal.js / mathjs formatter compatibility.
830
+ * When `n` is undefined the value is returned unchanged (no rounding).
831
+ */
832
+ toSignificantDigits(n?: number, roundingMode?: RoundingMode): BigNumber;
833
+ /**
834
+ * The decimal exponent of this number: `floor(log10(|x|))`.
835
+ *
836
+ * Matches Decimal.js semantics:
837
+ * - `12345` → `4` (5 digits → the most-significant place is 10^4)
838
+ * - `0.0123` → `-2` (first significant digit is at 10^-2)
839
+ * - `100` → `2`
840
+ * - `0.01` → `-2`
841
+ * - `0` → `0` (by convention; `isZero()` can be used to distinguish)
842
+ *
843
+ * For special values (NaN, ±Infinity) returns 0 — callers check
844
+ * `isFinite()` / `isNaN()` before using `.e`.
845
+ */
846
+ get e(): number;
770
847
  /**
771
848
  * Modulo (remainder after division)
772
849
  * Result has the same sign as the dividend (this).
@@ -906,6 +983,285 @@ declare const BIGNUMBER_E: BigNumber;
906
983
  declare const BIGNUMBER_LN2: BigNumber;
907
984
  declare const BIGNUMBER_LN10: BigNumber;
908
985
 
986
+ /**
987
+ * Unit definitions for the Unit type.
988
+ *
989
+ * The seven SI base units, plus common derived and imperial units. Each
990
+ * definition stores its multiplicative factor (to base SI) and dimensional
991
+ * exponents. Temperatures carry an additive offset for the K↔°C↔°F
992
+ * conversions.
993
+ *
994
+ * @module @danielsimonjr/mathts-core/types/unit-definitions
995
+ */
996
+ /**
997
+ * The seven SI base dimensions, expressed as a vector of (possibly fractional)
998
+ * exponents.
999
+ */
1000
+ interface Dimensions {
1001
+ /** Length, base unit metre */
1002
+ length: number;
1003
+ /** Mass, base unit kilogram */
1004
+ mass: number;
1005
+ /** Time, base unit second */
1006
+ time: number;
1007
+ /** Electric current, base unit ampere */
1008
+ current: number;
1009
+ /** Thermodynamic temperature, base unit kelvin */
1010
+ temperature: number;
1011
+ /** Amount of substance, base unit mole */
1012
+ amount: number;
1013
+ /** Luminous intensity, base unit candela */
1014
+ luminosity: number;
1015
+ }
1016
+ /**
1017
+ * The zero-dimensional vector (a dimensionless quantity).
1018
+ */
1019
+ declare const DIMENSIONLESS: Dimensions;
1020
+ /**
1021
+ * Construct a Dimensions record from a partial spec.
1022
+ *
1023
+ * Missing fields default to 0, so `dim({ length: 1 })` returns the dimension
1024
+ * vector for length.
1025
+ */
1026
+ declare function dim(partial: Partial<Dimensions>): Dimensions;
1027
+ /**
1028
+ * Definition of a single named unit.
1029
+ */
1030
+ interface UnitDef {
1031
+ /** Multiplicative factor: value-in-base = input * multiplier (+ offset). */
1032
+ multiplier: number;
1033
+ /** Additive offset, used for non-multiplicative units like °C and °F. */
1034
+ offset?: number;
1035
+ /** Dimensional signature. */
1036
+ dimensions: Dimensions;
1037
+ /** Whether SI prefixes (k, M, µ, …) may be applied to this notation. */
1038
+ prefixable?: boolean;
1039
+ }
1040
+ /**
1041
+ * The seven SI base units.
1042
+ */
1043
+ declare const BASE_UNITS: Record<string, UnitDef>;
1044
+ /**
1045
+ * Common derived units (SI named units, imperial units, and convenience units).
1046
+ *
1047
+ * This is *not* exhaustive — it covers the most common ~40 units needed for
1048
+ * dimensional-analysis tests. Add more as needed by downstream callers.
1049
+ */
1050
+ declare const DERIVED_UNITS: Record<string, UnitDef>;
1051
+ /**
1052
+ * Combined registry — both base and derived units in one map.
1053
+ */
1054
+ declare const ALL_UNITS: Record<string, UnitDef>;
1055
+ /**
1056
+ * Convenience aliases mapping common Unicode/ASCII variants to the canonical
1057
+ * notation key. Used by the parser; not part of the registered notation set.
1058
+ */
1059
+ declare const UNIT_ALIASES: Record<string, string>;
1060
+ /**
1061
+ * Lookup an exact (non-prefixed) unit definition.
1062
+ */
1063
+ declare function getUnitDef(name: string): UnitDef | undefined;
1064
+
1065
+ /**
1066
+ * Unit type — dimensional analysis, composition, conversion, and pretty-print.
1067
+ *
1068
+ * A {@link Unit} couples a numeric magnitude to a dimensional signature derived
1069
+ * from a registry of named units (see {@link ./unit-definitions}). Units are
1070
+ * **immutable**: every operation returns a new instance. The canonical
1071
+ * representation always stores the value in SI base units, regardless of how
1072
+ * the unit was constructed — so `new Unit(5, 'km').value === 5000` (metres).
1073
+ * The original notation is preserved on the instance for round-trip display.
1074
+ *
1075
+ * Design notes (intentional differences from mathjs's `Unit` class):
1076
+ * - **Immutable value semantics** instead of mutable JS prototype-class style.
1077
+ * - **No closure over a `math` instance.** Unit is self-contained — no
1078
+ * dependency on `addScalar`, `format`, `BigNumber`, etc. Values are plain
1079
+ * JS numbers.
1080
+ * - **`dimensions` is a struct** (a record over the seven SI bases) rather
1081
+ * than mathjs's array indexed by `BASE_DIMENSIONS`. Cheaper to work with in
1082
+ * TS, and lets the field be `Readonly<Dimensions>`.
1083
+ * - **Temperature offsets are honoured only for single-temperature-degree
1084
+ * units** (e.g. `°C` alone, not `°C/s`), matching mathjs but stated
1085
+ * explicitly here.
1086
+ *
1087
+ * @module @danielsimonjr/mathts-core/types/unit
1088
+ */
1089
+
1090
+ /**
1091
+ * Thrown when a unit operation requires matching dimensions but the operands
1092
+ * disagree. Carries the offending dimension vectors for debugging.
1093
+ */
1094
+ declare class DimensionMismatchError extends Error {
1095
+ readonly left: Dimensions;
1096
+ readonly right: Dimensions;
1097
+ readonly name = "DimensionMismatchError";
1098
+ constructor(left: Dimensions, right: Dimensions, op: string);
1099
+ }
1100
+ /** Thrown when a notation string cannot be parsed against the registry. */
1101
+ declare class UnitParseError extends Error {
1102
+ readonly name = "UnitParseError";
1103
+ constructor(notation: string, reason: string);
1104
+ }
1105
+ /**
1106
+ * A physical quantity: a numeric magnitude paired with a dimensional
1107
+ * signature derived from named units.
1108
+ *
1109
+ * Construction examples:
1110
+ * ```ts
1111
+ * new Unit(5, 'm'); // 5 metres
1112
+ * new Unit(3.5, 'km/h'); // 3.5 km/h
1113
+ * new Unit(20, '°C'); // 20 °C
1114
+ * new Unit(1, 'kg·m/s²'); // 1 newton (composed)
1115
+ * ```
1116
+ *
1117
+ * All instances are immutable; every operation returns a new {@link Unit}.
1118
+ * The `value` field is always in SI base units, so:
1119
+ *
1120
+ * ```ts
1121
+ * new Unit(5, 'km').value; // 5000 (canonical metres)
1122
+ * new Unit(20, '°C').value; // 293.15 (canonical kelvin)
1123
+ * ```
1124
+ */
1125
+ declare class Unit {
1126
+ /** Discriminator (matches the prototype-flag convention). */
1127
+ readonly type = "Unit";
1128
+ /** Used by `isUnit()` and typed-function dispatch. */
1129
+ readonly isUnit = true;
1130
+ /** Numeric magnitude in **SI base units**. */
1131
+ readonly value: number;
1132
+ /** Dimensional signature. */
1133
+ readonly dimensions: Readonly<Dimensions>;
1134
+ /** Original notation string, preserved for `toString()` round-trip. */
1135
+ readonly notation: string;
1136
+ /**
1137
+ * Construct a Unit from a numeric value and a notation string.
1138
+ *
1139
+ * The notation is parsed against the registered unit definitions in
1140
+ * {@link ./unit-definitions}. SI prefixes are applied automatically when
1141
+ * the bare notation doesn't match a registered unit. Compound expressions
1142
+ * like `"m/s²"`, `"kg·m/s²"`, and `"1/s"` are supported.
1143
+ *
1144
+ * @throws {UnitParseError} if `notation` cannot be parsed against the
1145
+ * registered unit definitions.
1146
+ */
1147
+ constructor(value: number, notation: string);
1148
+ /**
1149
+ * Internal construction shortcut from already-canonical fields. **Not
1150
+ * intended for direct use** — most callers should use the `(value,
1151
+ * notation)` form.
1152
+ */
1153
+ constructor(value: number, dimensions: Readonly<Dimensions>, notation: string);
1154
+ /**
1155
+ * Add two units. Requires identical dimensions.
1156
+ *
1157
+ * @throws {DimensionMismatchError} if dimensions differ.
1158
+ */
1159
+ add(other: Unit): Unit;
1160
+ /**
1161
+ * Subtract two units. Requires identical dimensions.
1162
+ *
1163
+ * @throws {DimensionMismatchError} if dimensions differ.
1164
+ */
1165
+ sub(other: Unit): Unit;
1166
+ /**
1167
+ * Multiply by another unit or a scalar. Dimensions add when multiplying by
1168
+ * another unit; unchanged when multiplying by a scalar.
1169
+ */
1170
+ mul(other: Unit | number): Unit;
1171
+ /**
1172
+ * Divide by another unit or a scalar. Dimensions subtract when dividing by
1173
+ * another unit; unchanged when dividing by a scalar.
1174
+ */
1175
+ div(other: Unit | number): Unit;
1176
+ /**
1177
+ * Raise to an integer or rational power. Dimensions scale by `n`.
1178
+ */
1179
+ pow(n: number): Unit;
1180
+ /**
1181
+ * Convert to a target unit. Dimensions must match.
1182
+ *
1183
+ * @throws {DimensionMismatchError} if `targetNotation`'s dimensions differ
1184
+ * from this unit's.
1185
+ */
1186
+ to(targetNotation: string): Unit;
1187
+ /**
1188
+ * Pick a unit (with SI prefix) that gives a magnitude closest to 1.
1189
+ *
1190
+ * Searches the unit registry for entries matching this unit's dimensions,
1191
+ * then applies each SI prefix in {@link BEST_PREFIXES} to find the
1192
+ * representation minimising `|log10(displayed value)|`.
1193
+ *
1194
+ * If no registered unit matches the dimensions, falls back to a synthetic
1195
+ * notation describing the dimensional vector.
1196
+ */
1197
+ toBest(): Unit;
1198
+ /** True iff dimensions and canonical value are equal. */
1199
+ equals(other: Unit): boolean;
1200
+ /** True iff dimensions match (values may differ). */
1201
+ dimensionsEqual(other: Unit): boolean;
1202
+ /**
1203
+ * Pretty-print. If `notation` is set (the common case), display the value
1204
+ * in that notation — otherwise emit a dimensional signature.
1205
+ */
1206
+ toString(): string;
1207
+ /** JSON-serialisable record. */
1208
+ toJSON(): {
1209
+ mathts: 'Unit';
1210
+ value: number;
1211
+ notation: string;
1212
+ };
1213
+ /**
1214
+ * Rehydrate from a JSON record produced by {@link toJSON}.
1215
+ *
1216
+ * @throws {UnitParseError} if `json.notation` cannot be parsed.
1217
+ */
1218
+ static fromJSON(json: {
1219
+ value: number;
1220
+ notation: string;
1221
+ }): Unit;
1222
+ /**
1223
+ * Parse a full unit expression (with optional leading numeric coefficient).
1224
+ *
1225
+ * Example: `Unit.parse('5 km/h')`.
1226
+ */
1227
+ static parse(input: string): Unit;
1228
+ }
1229
+
1230
+ /**
1231
+ * Duck-typing guard for {@link Unit}. Mirrors the convention used by
1232
+ * {@link Complex}, {@link Fraction}, and {@link BigNumber}.
1233
+ */
1234
+ declare function isUnit$1(value: unknown): value is Unit;
1235
+
1236
+ /**
1237
+ * SI prefixes for the Unit type.
1238
+ *
1239
+ * Maps single- and double-letter prefixes to their multiplicative factor in
1240
+ * base units. The full SI prefix range (from y = 1e-24 to Y = 1e24) is
1241
+ * supported, plus the binary prefixes used for digital information units.
1242
+ *
1243
+ * @module @danielsimonjr/mathts-core/types/unit-prefixes
1244
+ */
1245
+ /**
1246
+ * Standard SI prefixes (mass/length/energy/etc.).
1247
+ *
1248
+ * Note the ambiguity-resolution priority: longer prefixes (e.g. `da`)
1249
+ * must be tried before single-letter ones (`d`, `a`) in parsers.
1250
+ */
1251
+ declare const SI_PREFIXES: Record<string, number>;
1252
+ /**
1253
+ * Set of "good" prefixes to use in `toBest()` selection.
1254
+ *
1255
+ * Excludes `h`, `da`, `d`, `c` (commonly only used for centimeters and similar
1256
+ * legacy notations); using these in `toBest()` would produce awkward outputs
1257
+ * like "0.4 hg" instead of "40 g".
1258
+ */
1259
+ declare const BEST_PREFIXES: ReadonlyArray<string>;
1260
+ /**
1261
+ * Look up an SI prefix multiplier. Returns `undefined` if not a known prefix.
1262
+ */
1263
+ declare function getPrefix(name: string): number | undefined;
1264
+
909
1265
  /**
910
1266
  * MathTS typed-function Integration
911
1267
  *
@@ -975,6 +1331,10 @@ declare const isDenseMatrix: (x: unknown) => boolean;
975
1331
  declare const isSparseMatrix: (x: unknown) => boolean;
976
1332
  /**
977
1333
  * Check if value is a Unit
1334
+ *
1335
+ * Recognises both the native {@link Unit} class (which exposes `value`,
1336
+ * `dimensions`, and `notation`) and the legacy duck-typed shape used by
1337
+ * mathjs-compatibility shims (`{ value, unit, type }`).
978
1338
  */
979
1339
  declare const isUnit: (x: unknown) => boolean;
980
1340
  /**
@@ -1233,4 +1593,4 @@ declare const math: {
1233
1593
 
1234
1594
  declare const VERSION = "0.1.0";
1235
1595
 
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 };
1596
+ 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 };