@vielzeug/coins 1.0.2
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 +262 -0
- package/dist/_cache.cjs +2 -0
- package/dist/_cache.cjs.map +1 -0
- package/dist/_cache.d.ts +6 -0
- package/dist/_cache.d.ts.map +1 -0
- package/dist/_cache.js +14 -0
- package/dist/_cache.js.map +1 -0
- package/dist/_dev.cjs +2 -0
- package/dist/_dev.cjs.map +1 -0
- package/dist/_dev.d.ts +2 -0
- package/dist/_dev.d.ts.map +1 -0
- package/dist/_dev.js +9 -0
- package/dist/_dev.js.map +1 -0
- package/dist/coins.cjs +2 -0
- package/dist/coins.cjs.map +1 -0
- package/dist/coins.iife.js +2 -0
- package/dist/coins.iife.js.map +1 -0
- package/dist/coins.js +2 -0
- package/dist/coins.js.map +1 -0
- package/dist/errors.cjs +2 -0
- package/dist/errors.cjs.map +1 -0
- package/dist/errors.d.ts +52 -0
- package/dist/errors.d.ts.map +1 -0
- package/dist/errors.js +24 -0
- package/dist/errors.js.map +1 -0
- package/dist/exchange.cjs +2 -0
- package/dist/exchange.cjs.map +1 -0
- package/dist/exchange.d.ts +28 -0
- package/dist/exchange.d.ts.map +1 -0
- package/dist/exchange.js +18 -0
- package/dist/exchange.js.map +1 -0
- package/dist/format.cjs +2 -0
- package/dist/format.cjs.map +1 -0
- package/dist/format.d.ts +41 -0
- package/dist/format.d.ts.map +1 -0
- package/dist/format.js +104 -0
- package/dist/format.js.map +1 -0
- package/dist/index.cjs +1 -0
- package/dist/index.d.ts +7 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +6 -0
- package/dist/money.cjs +2 -0
- package/dist/money.cjs.map +1 -0
- package/dist/money.d.ts +247 -0
- package/dist/money.d.ts.map +1 -0
- package/dist/money.js +208 -0
- package/dist/money.js.map +1 -0
- package/dist/types.d.ts +60 -0
- package/dist/types.d.ts.map +1 -0
- package/dist/utils.cjs +2 -0
- package/dist/utils.cjs.map +1 -0
- package/dist/utils.d.ts +66 -0
- package/dist/utils.d.ts.map +1 -0
- package/dist/utils.js +66 -0
- package/dist/utils.js.map +1 -0
- package/package.json +39 -0
package/dist/money.js
ADDED
|
@@ -0,0 +1,208 @@
|
|
|
1
|
+
import { CoinsError as e, CurrencyMismatchError as t } from "./errors.js";
|
|
2
|
+
import { SCIENTIFIC_RE as n, applyRounding as r, expandScientific as i, getCurrencyDecimals as a, parseRational as o, pow10 as s, validateCurrencyCode as c } from "./utils.js";
|
|
3
|
+
import { warn as l } from "./_dev.js";
|
|
4
|
+
//#region src/money.ts
|
|
5
|
+
function u(e, t) {
|
|
6
|
+
let r = c(t);
|
|
7
|
+
if (typeof e == "bigint") return {
|
|
8
|
+
amount: e,
|
|
9
|
+
currency: r
|
|
10
|
+
};
|
|
11
|
+
if (typeof e == "number") {
|
|
12
|
+
let t = a(r), o = String(e), s = n.test(o) ? i(o) : o, c = s.indexOf("."), u = c === -1 ? 0 : s.length - c - 1;
|
|
13
|
+
return u > t && l(`money(): number input "${e}" has more decimal places (${u}) than ${r} supports (${t}). Use a decimal string to avoid IEEE-754 precision loss.`), {
|
|
14
|
+
amount: f(o, t),
|
|
15
|
+
currency: r
|
|
16
|
+
};
|
|
17
|
+
}
|
|
18
|
+
return {
|
|
19
|
+
amount: f(String(e), a(r)),
|
|
20
|
+
currency: r
|
|
21
|
+
};
|
|
22
|
+
}
|
|
23
|
+
function d(e, n) {
|
|
24
|
+
if (e.currency !== n.currency) throw new t(e.currency, n.currency);
|
|
25
|
+
}
|
|
26
|
+
function f(e, t) {
|
|
27
|
+
let { denominator: n, negative: i, numerator: a } = o(e), c = a * s(t), l = r(c / n, c % n, n, "half-away-from-zero");
|
|
28
|
+
return i ? -l : l;
|
|
29
|
+
}
|
|
30
|
+
function p(e, t) {
|
|
31
|
+
return {
|
|
32
|
+
amount: t,
|
|
33
|
+
currency: e.currency
|
|
34
|
+
};
|
|
35
|
+
}
|
|
36
|
+
function m(e) {
|
|
37
|
+
if (typeof e != "object" || !e) return !1;
|
|
38
|
+
let t = e;
|
|
39
|
+
return Object.hasOwn(t, "amount") && typeof t.amount == "bigint" && Object.hasOwn(t, "currency") && typeof t.currency == "string";
|
|
40
|
+
}
|
|
41
|
+
function h(e, t) {
|
|
42
|
+
return d(e, t), {
|
|
43
|
+
amount: e.amount + t.amount,
|
|
44
|
+
currency: e.currency
|
|
45
|
+
};
|
|
46
|
+
}
|
|
47
|
+
function g(e, t) {
|
|
48
|
+
return d(e, t), {
|
|
49
|
+
amount: e.amount - t.amount,
|
|
50
|
+
currency: e.currency
|
|
51
|
+
};
|
|
52
|
+
}
|
|
53
|
+
function _(e, t, n = "half-away-from-zero") {
|
|
54
|
+
let { denominator: i, negative: a, numerator: s } = o(String(t)), c = e.amount < 0n !== a, l = (e.amount < 0n ? -e.amount : e.amount) * s, u = r(l / i, l % i, i, n, c);
|
|
55
|
+
return {
|
|
56
|
+
amount: c ? -u : u,
|
|
57
|
+
currency: e.currency
|
|
58
|
+
};
|
|
59
|
+
}
|
|
60
|
+
function v(t, n, i = "half-away-from-zero") {
|
|
61
|
+
let { denominator: a, negative: s, numerator: c } = o(String(n));
|
|
62
|
+
if (c === 0n) throw new e("Division by zero");
|
|
63
|
+
let l = t.amount < 0n !== s, u = (t.amount < 0n ? -t.amount : t.amount) * a, d = r(u / c, u % c, c, i, l);
|
|
64
|
+
return {
|
|
65
|
+
amount: l ? -d : d,
|
|
66
|
+
currency: t.currency
|
|
67
|
+
};
|
|
68
|
+
}
|
|
69
|
+
function y(t, n) {
|
|
70
|
+
if (n.length === 0) throw new e("allocate requires at least one ratio");
|
|
71
|
+
let r = n.map((e) => o(String(e)));
|
|
72
|
+
if (r.some((e) => e.negative)) throw new e("All ratios must be non-negative");
|
|
73
|
+
if (!r.some((e) => e.numerator > 0n)) throw new e("At least one ratio must be positive");
|
|
74
|
+
let i = t.amount < 0n, a = i ? -t.amount : t.amount, s = r.reduce((e, t) => t.denominator > e ? t.denominator : e, 1n), c = r.map((e) => e.numerator * (s / e.denominator)), l = c.reduce((e, t) => e + t, 0n), u = [], d = [];
|
|
75
|
+
for (let e of c) {
|
|
76
|
+
let t = a * e;
|
|
77
|
+
u.push(t / l), d.push(t % l);
|
|
78
|
+
}
|
|
79
|
+
let f = n.map((e, t) => t).sort((e, t) => {
|
|
80
|
+
let n = d[t] - d[e];
|
|
81
|
+
return n > 0n ? 1 : n < 0n ? -1 : 0;
|
|
82
|
+
}), p = [...u], m = a - u.reduce((e, t) => e + t, 0n);
|
|
83
|
+
for (let e = 0; m > 0n; e++, m--) p[f[e]] += 1n;
|
|
84
|
+
return p.map((e) => ({
|
|
85
|
+
amount: i ? -e : e,
|
|
86
|
+
currency: t.currency
|
|
87
|
+
}));
|
|
88
|
+
}
|
|
89
|
+
function b(n) {
|
|
90
|
+
if (n.length === 0) throw new e("sum requires at least one Money value");
|
|
91
|
+
let r = n[0].currency;
|
|
92
|
+
for (let e = 1; e < n.length; e++) if (n[e].currency !== r) throw new t(r, n[e].currency);
|
|
93
|
+
return {
|
|
94
|
+
amount: n.reduce((e, t) => e + t.amount, 0n),
|
|
95
|
+
currency: r
|
|
96
|
+
};
|
|
97
|
+
}
|
|
98
|
+
function x(t) {
|
|
99
|
+
if (t.length === 0) throw new e("min requires at least one Money value");
|
|
100
|
+
let n = t[0];
|
|
101
|
+
for (let e = 1; e < t.length; e++) n = D(n, t[e]) <= 0 ? n : t[e];
|
|
102
|
+
return n;
|
|
103
|
+
}
|
|
104
|
+
function S(t) {
|
|
105
|
+
if (t.length === 0) throw new e("max requires at least one Money value");
|
|
106
|
+
let n = t[0];
|
|
107
|
+
for (let e = 1; e < t.length; e++) n = D(n, t[e]) >= 0 ? n : t[e];
|
|
108
|
+
return n;
|
|
109
|
+
}
|
|
110
|
+
function C(t, n) {
|
|
111
|
+
if (!Number.isInteger(n) || n <= 0) throw new e("splitEvenly requires a positive integer number of parts");
|
|
112
|
+
return y(t, Array.from({ length: n }, () => 1));
|
|
113
|
+
}
|
|
114
|
+
function w(n, r, i) {
|
|
115
|
+
if (n.currency !== r.currency || n.currency !== i.currency) throw new t(n.currency, n.currency === r.currency ? i.currency : r.currency);
|
|
116
|
+
if (D(r, i) > 0) throw new e(`clamp: lower (${B(r)} ${r.currency}) must be <= upper (${B(i)} ${i.currency})`);
|
|
117
|
+
return S([r, x([n, i])]);
|
|
118
|
+
}
|
|
119
|
+
function T(e) {
|
|
120
|
+
return {
|
|
121
|
+
amount: e.amount < 0n ? -e.amount : e.amount,
|
|
122
|
+
currency: e.currency
|
|
123
|
+
};
|
|
124
|
+
}
|
|
125
|
+
function E(e) {
|
|
126
|
+
return {
|
|
127
|
+
amount: -e.amount,
|
|
128
|
+
currency: e.currency
|
|
129
|
+
};
|
|
130
|
+
}
|
|
131
|
+
function D(e, t) {
|
|
132
|
+
return d(e, t), e.amount < t.amount ? -1 : +(e.amount > t.amount);
|
|
133
|
+
}
|
|
134
|
+
function O(e, t) {
|
|
135
|
+
return e.currency === t.currency && e.amount === t.amount;
|
|
136
|
+
}
|
|
137
|
+
function k(e, t) {
|
|
138
|
+
return D(e, t) > 0;
|
|
139
|
+
}
|
|
140
|
+
function A(e, t) {
|
|
141
|
+
return D(e, t) >= 0;
|
|
142
|
+
}
|
|
143
|
+
function j(e, t) {
|
|
144
|
+
return D(e, t) < 0;
|
|
145
|
+
}
|
|
146
|
+
function M(e, t) {
|
|
147
|
+
return D(e, t) <= 0;
|
|
148
|
+
}
|
|
149
|
+
function N(e) {
|
|
150
|
+
return e.amount === 0n;
|
|
151
|
+
}
|
|
152
|
+
function P(e) {
|
|
153
|
+
return e.amount > 0n;
|
|
154
|
+
}
|
|
155
|
+
function F(e) {
|
|
156
|
+
return e.amount < 0n;
|
|
157
|
+
}
|
|
158
|
+
function I(e) {
|
|
159
|
+
return e.amount >= 0n;
|
|
160
|
+
}
|
|
161
|
+
function L(e) {
|
|
162
|
+
return e.amount <= 0n;
|
|
163
|
+
}
|
|
164
|
+
function R(e) {
|
|
165
|
+
return {
|
|
166
|
+
amount: String(e.amount),
|
|
167
|
+
currency: e.currency
|
|
168
|
+
};
|
|
169
|
+
}
|
|
170
|
+
function z(t) {
|
|
171
|
+
let n = c(t.currency);
|
|
172
|
+
if (typeof t.amount != "string") throw new e(`Invalid money amount in JSON: ${String(t.amount)} (expected an integer string, e.g. '123456')`);
|
|
173
|
+
let r;
|
|
174
|
+
try {
|
|
175
|
+
r = BigInt(t.amount);
|
|
176
|
+
} catch {
|
|
177
|
+
throw new e(`Invalid money amount in JSON: "${t.amount}" (expected an integer string, e.g. '123456')`);
|
|
178
|
+
}
|
|
179
|
+
return {
|
|
180
|
+
amount: r,
|
|
181
|
+
currency: n
|
|
182
|
+
};
|
|
183
|
+
}
|
|
184
|
+
function B(e) {
|
|
185
|
+
let t = a(e.currency);
|
|
186
|
+
if (t === 0) return String(e.amount);
|
|
187
|
+
let n = e.amount < 0n, r = n ? -e.amount : e.amount, i = s(t), o = r / i, c = (r % i).toString().padStart(t, "0");
|
|
188
|
+
return `${n ? "-" : ""}${o}.${c}`;
|
|
189
|
+
}
|
|
190
|
+
function V(e) {
|
|
191
|
+
let t = a(e.currency);
|
|
192
|
+
return Number(e.amount) / Number(s(t));
|
|
193
|
+
}
|
|
194
|
+
function H(t, n, i = "half-away-from-zero") {
|
|
195
|
+
if (!Number.isInteger(n) || n < 0) throw new e(`roundTo: places must be a non-negative integer, got ${n}`);
|
|
196
|
+
let o = a(t.currency);
|
|
197
|
+
if (n > o) throw new e(`roundTo: places (${n}) exceeds the decimal places for ${t.currency} (${o})`);
|
|
198
|
+
if (n === o) return t;
|
|
199
|
+
let c = s(o - n), l = t.amount < 0n, u = l ? -t.amount : t.amount, d = r(u / c, u % c, c, i, l);
|
|
200
|
+
return {
|
|
201
|
+
amount: l ? -d : d,
|
|
202
|
+
currency: t.currency
|
|
203
|
+
};
|
|
204
|
+
}
|
|
205
|
+
//#endregion
|
|
206
|
+
export { T as abs, h as add, y as allocate, w as clamp, D as compare, v as divide, z as fromJSON, k as greaterThan, A as greaterThanOrEqual, O as isEqual, m as isMoney, F as isNegative, I as isNonNegative, L as isNonPositive, P as isPositive, N as isZero, j as lessThan, M as lessThanOrEqual, S as max, x as min, u as money, _ as multiply, E as negate, H as roundTo, C as splitEvenly, g as subtract, b as sum, B as toDecimal, R as toJSON, V as toNumber, p as withAmount };
|
|
207
|
+
|
|
208
|
+
//# sourceMappingURL=money.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"money.js","names":[],"sources":["../src/money.ts"],"sourcesContent":["import type { CurrencyCode, Money, MoneyJSON, RoundingMode } from './types';\n\nimport { warn } from './_dev';\nimport { CoinsError, CurrencyMismatchError } from './errors';\nimport {\n applyRounding,\n expandScientific,\n getCurrencyDecimals,\n parseRational,\n pow10,\n SCIENTIFIC_RE,\n validateCurrencyCode,\n} from './utils';\n\nexport { CoinsError, CurrencyMismatchError, InvalidCurrencyError } from './errors';\n\n// ─── Factories ───────────────────────────────────────────────────────────────\n\n/**\n * Creates a `Money` value from a decimal string, number, or raw bigint minor units.\n * Validates the currency code — throws `InvalidCurrencyError` for unrecognised ISO 4217 codes.\n *\n * - **string** `'1234.56'` → parsed losslessly; respects the currency's decimal places.\n * - **number** `1234.56` → converted via `String()` first; inherits IEEE-754 limits.\n * Prefer strings when precision matters.\n * - **bigint** `123456n` → used as-is (already in minor units).\n *\n * @example\n * ```ts\n * money('1234.56', 'USD') // { amount: 123456n, currency: 'USD' }\n * money(1234, 'JPY') // { amount: 1234n, currency: 'JPY' }\n * money(123456n, 'USD') // { amount: 123456n, currency: 'USD' }\n * ```\n */\nexport function money(amount: bigint | number | string, currency: CurrencyCode): Money {\n const validCurrency = validateCurrencyCode(currency);\n\n if (typeof amount === 'bigint') {\n return { amount, currency: validCurrency };\n }\n\n if (typeof amount === 'number') {\n const decimals = getCurrencyDecimals(validCurrency);\n const str = String(amount);\n // Expand scientific notation (e.g. String(1e-7) === '1e-7') before measuring fraction\n // length — otherwise inputs like 1e-7 report 0 fractional digits and skip the warning\n // below despite having far more precision than the currency supports.\n const normalized = SCIENTIFIC_RE.test(str) ? expandScientific(str) : str;\n const dotIndex = normalized.indexOf('.');\n const fracLen = dotIndex === -1 ? 0 : normalized.length - dotIndex - 1;\n\n if (fracLen > decimals) {\n warn(\n `money(): number input \"${amount}\" has more decimal places (${fracLen}) than ${validCurrency} supports (${decimals}). ` +\n `Use a decimal string to avoid IEEE-754 precision loss.`,\n );\n }\n\n // getCurrencyDecimals is cached from the validateCurrencyCode call above.\n return { amount: parseToMinorUnits(str, decimals), currency: validCurrency };\n }\n\n // getCurrencyDecimals is cached from the validateCurrencyCode call above.\n return { amount: parseToMinorUnits(String(amount), getCurrencyDecimals(validCurrency)), currency: validCurrency };\n}\n\n// ─── Internal ─────────────────────────────────────────────────────────────────\n\nfunction assertSameCurrency(a: Money, b: Money): void {\n if (a.currency !== b.currency) {\n throw new CurrencyMismatchError(a.currency, b.currency);\n }\n}\n\n/**\n * Converts a decimal string to minor units for the given decimal precision.\n * Uses parseRational + applyRounding to share the single rounding implementation.\n */\nfunction parseToMinorUnits(str: string, decimals: number): bigint {\n const { denominator, negative, numerator } = parseRational(str);\n // numerator/denominator × 10^decimals = numerator × 10^decimals / denominator\n const scale = pow10(decimals);\n const raw = numerator * scale;\n const quotient = raw / denominator;\n const result = applyRounding(quotient, raw % denominator, denominator, 'half-away-from-zero');\n\n return negative ? -result : result;\n}\n\n/**\n * Creates a new `Money` value with the given `amount` and the same currency as `m`.\n * Useful when you compute a raw `bigint` amount externally and need to wrap it\n * back into a `Money` value without re-validating the currency.\n *\n * @example\n * ```ts\n * const price = money('9.99', 'USD');\n * withAmount(price, 1999n) // { amount: 1999n, currency: 'USD' }\n * ```\n */\nexport function withAmount(m: Money, amount: bigint): Money {\n return { amount, currency: m.currency };\n}\n\n/**\n * Type guard that returns `true` if `value` is a `Money`-shaped object\n * (has a `bigint` `amount` and a `string` `currency`).\n * Useful for narrowing unknown payloads from APIs or deserialized storage.\n *\n * Note: does **not** validate the currency code — use `money(0n, currency)` or\n * `validateCurrencyCode()` if you also need to confirm it is a recognized ISO 4217 code.\n *\n * @example\n * ```ts\n * isMoney({ amount: 100n, currency: 'USD' }) // true\n * isMoney({ amount: 1.5, currency: 'USD' }) // false\n * isMoney(null) // false\n * ```\n */\nexport function isMoney(value: unknown): value is Money {\n if (typeof value !== 'object' || value === null) return false;\n\n const v = value as Record<string, unknown>;\n\n return (\n Object.hasOwn(v, 'amount') &&\n typeof v.amount === 'bigint' &&\n Object.hasOwn(v, 'currency') &&\n typeof v.currency === 'string'\n );\n}\n\n// ─── Arithmetic ──────────────────────────────────────────────────────────────\n\n/** Adds two `Money` values. Throws if their currencies differ. */\nexport function add(a: Money, b: Money): Money {\n assertSameCurrency(a, b);\n\n return { amount: a.amount + b.amount, currency: a.currency };\n}\n\n/** Subtracts `b` from `a`. Throws if their currencies differ. */\nexport function subtract(a: Money, b: Money): Money {\n assertSameCurrency(a, b);\n\n return { amount: a.amount - b.amount, currency: a.currency };\n}\n\n/**\n * Multiplies a `Money` value by a scalar factor.\n * The factor can be a decimal string (lossless) or a number.\n *\n * @param mode Rounding mode for fractional minor units. Defaults to `'half-away-from-zero'`.\n *\n * @example\n * ```ts\n * multiply(money('100.00', 'USD'), '1.5') // $150.00\n * multiply(money('1.00', 'USD'), '0.339', 'floor') // $0.33\n * multiply(money('1.00', 'USD'), '0.339', 'ceiling') // $0.34\n * ```\n */\nexport function multiply(m: Money, factor: number | string, mode: RoundingMode = 'half-away-from-zero'): Money {\n const { denominator, negative: factorNegative, numerator } = parseRational(String(factor));\n const negative = m.amount < 0n !== factorNegative;\n const absAmount = m.amount < 0n ? -m.amount : m.amount;\n const raw = absAmount * numerator;\n const quotient = raw / denominator;\n const result = applyRounding(quotient, raw % denominator, denominator, mode, negative);\n\n return { amount: negative ? -result : result, currency: m.currency };\n}\n\n/**\n * Divides a `Money` value by a scalar divisor.\n * The divisor can be a decimal string (lossless) or a number.\n *\n * @param mode Rounding mode for fractional minor units. Defaults to `'half-away-from-zero'`.\n * @throws {CoinsError} On division by zero.\n *\n * @example\n * ```ts\n * divide(money('100.00', 'USD'), 3) // $33.33\n * divide(money('100.00', 'USD'), 3, 'ceiling') // $33.34\n * ```\n */\nexport function divide(m: Money, divisor: number | string, mode: RoundingMode = 'half-away-from-zero'): Money {\n const { denominator: parsedDenom, negative: divisorNegative, numerator } = parseRational(String(divisor));\n\n if (numerator === 0n) throw new CoinsError('Division by zero');\n\n const negative = m.amount < 0n !== divisorNegative;\n const absAmount = m.amount < 0n ? -m.amount : m.amount;\n // Dividing by (numerator/parsedDenom) = multiplying by (parsedDenom/numerator).\n const raw = absAmount * parsedDenom;\n const quotient = raw / numerator;\n const result = applyRounding(quotient, raw % numerator, numerator, mode, negative);\n\n return { amount: negative ? -result : result, currency: m.currency };\n}\n\n/**\n * Distributes `money` across `ratios` without losing or gaining a single minor unit.\n * Accepts both number and string ratios — use strings for lossless decimal weights.\n *\n * Uses the Largest Remainder Method: each share gets its floor allocation first,\n * then any remainder units are assigned one-by-one to the shares with the largest\n * fractional parts, breaking ties by original index (stable, left-to-right).\n *\n * Throws if `ratios` is empty, contains negative values (including negative strings like `'-0.5'`), or sums to zero.\n *\n * @example\n * ```ts\n * allocate(money('10.00', 'USD'), [1, 1, 1])\n * // → [$3.34, $3.33, $3.33] (not three × $3.33 — that loses a penny)\n *\n * allocate(money('10.00', 'USD'), ['0.3', '0.7'])\n * // → [$3.00, $7.00]\n * ```\n */\nexport function allocate(m: Money, ratios: readonly (number | string)[]): [Money, ...Money[]] {\n if (ratios.length === 0) throw new CoinsError('allocate requires at least one ratio');\n\n const parsedRatios = ratios.map((r) => parseRational(String(r)));\n\n if (parsedRatios.some((p) => p.negative)) throw new CoinsError('All ratios must be non-negative');\n\n if (!parsedRatios.some((p) => p.numerator > 0n)) throw new CoinsError('At least one ratio must be positive');\n\n const negative = m.amount < 0n;\n const absAmount = negative ? -m.amount : m.amount;\n\n // All denominators are powers of 10; the max is their LCM — use it to normalise weights to integers.\n const maxDenominator = parsedRatios.reduce((max, p) => (p.denominator > max ? p.denominator : max), 1n);\n const bigWeights = parsedRatios.map((p) => p.numerator * (maxDenominator / p.denominator));\n const bigTotal = bigWeights.reduce((a, b) => a + b, 0n);\n\n // Floor allocation + fractional remainders.\n const floors: bigint[] = [];\n const fracRemainders: bigint[] = [];\n\n for (const w of bigWeights) {\n const ideal = absAmount * w;\n\n floors.push(ideal / bigTotal);\n fracRemainders.push(ideal % bigTotal);\n }\n\n // Distribute leftover units to the shares with the largest fractional remainders.\n // Relies on V8/SpiderMonkey's stable sort (ECMAScript 2019+ spec-mandated): ties\n // in fractional remainders are broken by original index (left-to-right), ensuring\n // deterministic output for equal-weight ratios (e.g. [1, 1, 1]).\n const indices = ratios\n .map((_, i) => i)\n .sort((a, b) => {\n const diff = fracRemainders[b]! - fracRemainders[a]!;\n\n return diff > 0n ? 1 : diff < 0n ? -1 : 0;\n });\n\n const result = [...floors];\n // `remaining` is always < ratios.length (at most one unit per share), safe for this loop.\n let remaining = absAmount - floors.reduce((a, b) => a + b, 0n);\n\n for (let i = 0; remaining > 0n; i++, remaining--) {\n result[indices[i]!]! += 1n;\n }\n\n return result.map((amount) => ({ amount: negative ? -amount : amount, currency: m.currency })) as [Money, ...Money[]];\n}\n\n// ─── Aggregates ──────────────────────────────────────────────────────────────\n\n/**\n * Sums an array of `Money` values. Throws if the array is empty or currencies differ.\n *\n * @example\n * ```ts\n * sum([money('1.00', 'USD'), money('2.50', 'USD')]) // $3.50\n * ```\n */\nexport function sum(moneys: readonly Money[]): Money {\n if (moneys.length === 0) throw new CoinsError('sum requires at least one Money value');\n\n const currency = moneys[0]!.currency;\n\n for (let i = 1; i < moneys.length; i++) {\n if (moneys[i]!.currency !== currency) {\n throw new CurrencyMismatchError(currency, moneys[i]!.currency);\n }\n }\n\n return { amount: moneys.reduce((acc, m) => acc + m.amount, 0n), currency };\n}\n\n/**\n * Returns the smallest `Money` value from a non-empty array. Throws if currencies differ.\n *\n * @example\n * ```ts\n * min([money('3.00', 'USD'), money('1.00', 'USD'), money('2.00', 'USD')]) // $1.00\n * ```\n */\nexport function min(moneys: readonly Money[]): Money {\n if (moneys.length === 0) throw new CoinsError('min requires at least one Money value');\n\n let result = moneys[0]!;\n\n for (let i = 1; i < moneys.length; i++) result = compare(result, moneys[i]!) <= 0 ? result : moneys[i]!;\n\n return result;\n}\n\n/**\n * Returns the largest `Money` value from a non-empty array. Throws if currencies differ.\n *\n * @example\n * ```ts\n * max([money('1.00', 'USD'), money('3.00', 'USD'), money('2.00', 'USD')]) // $3.00\n * ```\n */\nexport function max(moneys: readonly Money[]): Money {\n if (moneys.length === 0) throw new CoinsError('max requires at least one Money value');\n\n let result = moneys[0]!;\n\n for (let i = 1; i < moneys.length; i++) result = compare(result, moneys[i]!) >= 0 ? result : moneys[i]!;\n\n return result;\n}\n\n/**\n * Splits `money` into `parts` equal shares without losing or gaining a single minor unit.\n * Equivalent to `allocate(money, Array.from({ length: parts }, () => 1))`.\n *\n * @throws {CoinsError} If `parts` is not a positive integer (≥ 1).\n *\n * @example\n * ```ts\n * splitEvenly(money('10.00', 'USD'), 3)\n * // → [$3.34, $3.33, $3.33]\n * ```\n */\nexport function splitEvenly(m: Money, parts: number): [Money, ...Money[]] {\n if (!Number.isInteger(parts) || parts <= 0) {\n throw new CoinsError('splitEvenly requires a positive integer number of parts');\n }\n\n return allocate(\n m,\n Array.from({ length: parts }, () => 1),\n );\n}\n\n/**\n * Clamps `m` to the inclusive range `[lower, upper]`.\n *\n * @throws {CurrencyMismatchError} If `m`, `lower`, or `upper` have different currencies.\n * @throws {CoinsError} If `lower > upper`.\n *\n * @example\n * ```ts\n * clamp(money('5.00', 'USD'), money('1.00', 'USD'), money('10.00', 'USD')) // $5.00\n * clamp(money('0.00', 'USD'), money('1.00', 'USD'), money('10.00', 'USD')) // $1.00\n * clamp(money('15.00', 'USD'), money('1.00', 'USD'), money('10.00', 'USD')) // $10.00\n * ```\n */\nexport function clamp(m: Money, lower: Money, upper: Money): Money {\n // Validate currency consistency upfront so the error always names the mismatch,\n // rather than surfacing mid-computation from min() or max().\n if (m.currency !== lower.currency || m.currency !== upper.currency) {\n throw new CurrencyMismatchError(m.currency, m.currency !== lower.currency ? lower.currency : upper.currency);\n }\n\n if (compare(lower, upper) > 0) {\n throw new CoinsError(\n `clamp: lower (${toDecimal(lower)} ${lower.currency}) must be <= upper (${toDecimal(upper)} ${upper.currency})`,\n );\n }\n\n return max([lower, min([m, upper])]);\n}\n\n// ─── Unary ───────────────────────────────────────────────────────────────────\n\n/** Returns the absolute value of `money`. Negative amounts become positive. */\nexport function abs(m: Money): Money {\n return { amount: m.amount < 0n ? -m.amount : m.amount, currency: m.currency };\n}\n\n/** Returns `money` with its sign flipped. */\nexport function negate(m: Money): Money {\n return { amount: -m.amount, currency: m.currency };\n}\n\n// ─── Comparison ──────────────────────────────────────────────────────────────\n\n/**\n * Compares two `Money` values. Returns `-1`, `0`, or `1`.\n * Throws if their currencies differ.\n */\nexport function compare(a: Money, b: Money): -1 | 0 | 1 {\n assertSameCurrency(a, b);\n\n if (a.amount < b.amount) return -1;\n\n if (a.amount > b.amount) return 1;\n\n return 0;\n}\n\n/**\n * Returns `true` if both `Money` values have the same currency and amount.\n * Returns `false` if currencies differ — safe to use in `.filter()` and conditional chains.\n */\nexport function isEqual(a: Money, b: Money): boolean {\n return a.currency === b.currency && a.amount === b.amount;\n}\n\n/** Returns `true` if `a` is strictly greater than `b`. Throws on currency mismatch. */\nexport function greaterThan(a: Money, b: Money): boolean {\n return compare(a, b) > 0;\n}\n\n/** Returns `true` if `a` is greater than or equal to `b`. Throws on currency mismatch. */\nexport function greaterThanOrEqual(a: Money, b: Money): boolean {\n return compare(a, b) >= 0;\n}\n\n/** Returns `true` if `a` is strictly less than `b`. Throws on currency mismatch. */\nexport function lessThan(a: Money, b: Money): boolean {\n return compare(a, b) < 0;\n}\n\n/** Returns `true` if `a` is less than or equal to `b`. Throws on currency mismatch. */\nexport function lessThanOrEqual(a: Money, b: Money): boolean {\n return compare(a, b) <= 0;\n}\n\n// ─── Predicates ──────────────────────────────────────────────────────────────\n\n/** Returns `true` if the amount is exactly zero. */\nexport function isZero(m: Money): boolean {\n return m.amount === 0n;\n}\n\n/** Returns `true` if the amount is strictly positive (> 0). */\nexport function isPositive(m: Money): boolean {\n return m.amount > 0n;\n}\n\n/** Returns `true` if the amount is strictly negative (< 0). */\nexport function isNegative(m: Money): boolean {\n return m.amount < 0n;\n}\n\n/** Returns `true` if the amount is zero or positive (>= 0). */\nexport function isNonNegative(m: Money): boolean {\n return m.amount >= 0n;\n}\n\n/** Returns `true` if the amount is zero or negative (<= 0). */\nexport function isNonPositive(m: Money): boolean {\n return m.amount <= 0n;\n}\n\n// ─── Serialization ───────────────────────────────────────────────────────────\n\n/**\n * Serializes a `Money` value to a plain-object JSON-safe form.\n * `amount` is a bigint string (e.g. `'123456'`) to avoid `JSON.stringify` throwing.\n *\n * @example\n * ```ts\n * toJSON(money('1234.56', 'USD')) // { amount: '123456', currency: 'USD' }\n * JSON.stringify(toJSON(price)) // '{\"amount\":\"123456\",\"currency\":\"USD\"}'\n * ```\n */\nexport function toJSON(m: Money): MoneyJSON {\n return { amount: String(m.amount), currency: m.currency };\n}\n\n/**\n * Deserializes a `MoneyJSON` object back into a `Money` value.\n * Validates the currency code and the amount string.\n *\n * @example\n * ```ts\n * fromJSON({ amount: '123456', currency: 'USD' }) // { amount: 123456n, currency: 'USD' }\n * ```\n */\nexport function fromJSON(json: MoneyJSON): Money {\n const validCurrency = validateCurrencyCode(json.currency);\n\n if (typeof json.amount !== 'string') {\n throw new CoinsError(\n `Invalid money amount in JSON: ${String(json.amount)} (expected an integer string, e.g. '123456')`,\n );\n }\n\n let amount: bigint;\n\n try {\n amount = BigInt(json.amount);\n } catch {\n throw new CoinsError(`Invalid money amount in JSON: \"${json.amount}\" (expected an integer string, e.g. '123456')`);\n }\n\n return { amount, currency: validCurrency };\n}\n\n/**\n * Serializes a `Money` value to a decimal string (e.g. `'1234.56'`).\n * Round-trips losslessly with `money()`.\n *\n * @example\n * ```ts\n * toDecimal(money('1234.56', 'USD')) // '1234.56'\n * toDecimal(money(5n, 'USD')) // '0.05'\n * toDecimal(money(1234n, 'JPY')) // '1234'\n * ```\n */\nexport function toDecimal(m: Money): string {\n const decimals = getCurrencyDecimals(m.currency);\n\n if (decimals === 0) return String(m.amount);\n\n const negative = m.amount < 0n;\n const abs = negative ? -m.amount : m.amount;\n const scale = pow10(decimals);\n const whole = abs / scale;\n const frac = (abs % scale).toString().padStart(decimals, '0');\n\n return `${negative ? '-' : ''}${whole}.${frac}`;\n}\n\n/**\n * Converts a `Money` value to a floating-point number.\n * Useful for charting and display; **not** for arithmetic (lossy).\n *\n * @example\n * ```ts\n * toNumber(money('1234.56', 'USD')) // 1234.56\n * ```\n */\nexport function toNumber(m: Money): number {\n const decimals = getCurrencyDecimals(m.currency);\n\n return Number(m.amount) / Number(pow10(decimals));\n}\n\n// ─── Rounding ─────────────────────────────────────────────────────────────────\n\n/**\n * Rounds a `Money` value to fewer decimal places than the currency's default.\n * `places` must be a non-negative integer in the range `0..currencyDecimals`.\n *\n * Useful for display purposes (e.g. rounding USD to whole dollars).\n * @throws {CoinsError} If `places` is out of the allowed range.\n *\n * @param mode Rounding mode. Defaults to `'half-away-from-zero'`.\n *\n * @example\n * ```ts\n * roundTo(money('1234.56', 'USD'), 0) // $1235 (whole dollars)\n * roundTo(money('1234.56', 'USD'), 1) // $1234.6\n * roundTo(money('1234.56', 'USD'), 1, 'floor') // $1234.5\n * roundTo(money('1234', 'JPY'), 0) // ¥1234 (no-op: JPY is already 0-decimal)\n * ```\n */\nexport function roundTo(m: Money, places: number, mode: RoundingMode = 'half-away-from-zero'): Money {\n if (!Number.isInteger(places) || places < 0) {\n throw new CoinsError(`roundTo: places must be a non-negative integer, got ${places}`);\n }\n\n const currencyDecimals = getCurrencyDecimals(m.currency);\n\n if (places > currencyDecimals) {\n throw new CoinsError(\n `roundTo: places (${places}) exceeds the decimal places for ${m.currency} (${currencyDecimals})`,\n );\n }\n\n if (places === currencyDecimals) return m;\n\n const drop = currencyDecimals - places;\n const divisor = pow10(drop);\n const negative = m.amount < 0n;\n const absAmount = negative ? -m.amount : m.amount;\n const quotient = absAmount / divisor;\n const remainder = absAmount % divisor;\n const rounded = applyRounding(quotient, remainder, divisor, mode, negative);\n\n return { amount: negative ? -rounded : rounded, currency: m.currency };\n}\n"],"mappings":";;;;AAkCA,SAAgB,EAAM,GAAkC,GAA+B;CACrF,IAAM,IAAgB,EAAqB,CAAQ;CAEnD,IAAI,OAAO,KAAW,UACpB,OAAO;EAAE;EAAQ,UAAU;CAAc;CAG3C,IAAI,OAAO,KAAW,UAAU;EAC9B,IAAM,IAAW,EAAoB,CAAa,GAC5C,IAAM,OAAO,CAAM,GAInB,IAAa,EAAc,KAAK,CAAG,IAAI,EAAiB,CAAG,IAAI,GAC/D,IAAW,EAAW,QAAQ,GAAG,GACjC,IAAU,MAAa,KAAK,IAAI,EAAW,SAAS,IAAW;EAUrE,OARI,IAAU,KACZ,EACE,0BAA0B,EAAO,6BAA6B,EAAQ,SAAS,EAAc,aAAa,EAAS,0DAErH,GAIK;GAAE,QAAQ,EAAkB,GAAK,CAAQ;GAAG,UAAU;EAAc;CAC7E;CAGA,OAAO;EAAE,QAAQ,EAAkB,OAAO,CAAM,GAAG,EAAoB,CAAa,CAAC;EAAG,UAAU;CAAc;AAClH;AAIA,SAAS,EAAmB,GAAU,GAAgB;CACpD,IAAI,EAAE,aAAa,EAAE,UACnB,MAAM,IAAI,EAAsB,EAAE,UAAU,EAAE,QAAQ;AAE1D;AAMA,SAAS,EAAkB,GAAa,GAA0B;CAChE,IAAM,EAAE,gBAAa,aAAU,iBAAc,EAAc,CAAG,GAGxD,IAAM,IADE,EAAM,CACI,GAElB,IAAS,EADE,IAAM,GACgB,IAAM,GAAa,GAAa,qBAAqB;CAE5F,OAAO,IAAW,CAAC,IAAS;AAC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AAM,IAAI,EACR,oBAAoB,EAAO,mCAAmC,EAAE,SAAS,IAAI,EAAiB,EAChG;CAGF,IAAI,MAAW,GAAkB,OAAO;CAGxC,IAAM,IAAU,EADH,IAAmB,CACN,GACpB,IAAW,EAAE,SAAS,IACtB,IAAY,IAAW,CAAC,EAAE,SAAS,EAAE,QAGrC,IAAU,EAFC,IAAY,GACX,IAAY,GACqB,GAAS,GAAM,CAAQ;CAE1E,OAAO;EAAE,QAAQ,IAAW,CAAC,IAAU;EAAS,UAAU,EAAE;CAAS;AACvE"}
|
package/dist/types.d.ts
ADDED
|
@@ -0,0 +1,60 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* A validated ISO 4217 currency code string (e.g. `'USD'`, `'EUR'`, `'JPY'`).
|
|
3
|
+
* Plain string alias — runtime validation is performed by every function that
|
|
4
|
+
* accepts a currency, and violations throw `InvalidCurrencyError`.
|
|
5
|
+
*/
|
|
6
|
+
export type CurrencyCode = string;
|
|
7
|
+
/** A monetary value. `amount` is stored as bigint minor units (e.g. cents for USD). */
|
|
8
|
+
export type Money = {
|
|
9
|
+
readonly amount: bigint;
|
|
10
|
+
readonly currency: CurrencyCode;
|
|
11
|
+
};
|
|
12
|
+
/**
|
|
13
|
+
* An exchange rate between two currencies.
|
|
14
|
+
* - `from` must match the `currency` of the `Money` passed to `exchange()`.
|
|
15
|
+
* Since every `Money.currency` is already a validated ISO 4217 code, a matching
|
|
16
|
+
* `from` is implicitly valid.
|
|
17
|
+
* - `to` is validated as a recognised ISO 4217 code by `exchange()` before returning.
|
|
18
|
+
* - `rate` is a decimal string (e.g. `'0.847532'`) or number, for symmetry with
|
|
19
|
+
* `multiply()`/`divide()`. Prefer a string when precision matters — a number is
|
|
20
|
+
* converted via `String()` first and inherits IEEE-754 limits.
|
|
21
|
+
*/
|
|
22
|
+
export type ExchangeRate = {
|
|
23
|
+
readonly from: CurrencyCode;
|
|
24
|
+
readonly rate: number | string;
|
|
25
|
+
readonly to: CurrencyCode;
|
|
26
|
+
};
|
|
27
|
+
/** Options for `format()`. */
|
|
28
|
+
export type FormatOptions = {
|
|
29
|
+
locale?: string;
|
|
30
|
+
maximumFractionDigits?: number;
|
|
31
|
+
minimumFractionDigits?: number;
|
|
32
|
+
style?: 'code' | 'name' | 'narrowSymbol' | 'symbol';
|
|
33
|
+
};
|
|
34
|
+
/**
|
|
35
|
+
* Rounding mode for operations that produce fractional minor units.
|
|
36
|
+
*
|
|
37
|
+
* | Mode | Description |
|
|
38
|
+
* |---|---|
|
|
39
|
+
* | `'ceiling'` | Toward +∞ (up for positives, truncate for negatives) |
|
|
40
|
+
* | `'down'` | Toward zero (truncate, regardless of sign) |
|
|
41
|
+
* | `'floor'` | Toward −∞ (truncate for positives, down for negatives) |
|
|
42
|
+
* | `'half-away-from-zero'` | Round half away from zero (default, common in finance) |
|
|
43
|
+
* | `'half-even'` | Round half to even (banker's rounding, minimises cumulative error) |
|
|
44
|
+
* | `'up'` | Away from zero (regardless of sign) |
|
|
45
|
+
*/
|
|
46
|
+
export type RoundingMode = 'ceiling' | 'down' | 'floor' | 'half-away-from-zero' | 'half-even' | 'up';
|
|
47
|
+
/** JSON-safe representation of `Money`. `amount` is a decimal integer string to avoid bigint serialization issues. */
|
|
48
|
+
export type MoneyJSON = {
|
|
49
|
+
amount: string;
|
|
50
|
+
currency: string;
|
|
51
|
+
};
|
|
52
|
+
/**
|
|
53
|
+
* A single semantic part of a formatted money string, as returned by `formatParts()`.
|
|
54
|
+
* Useful for custom rendering (e.g. applying different CSS to symbol, integer, fraction).
|
|
55
|
+
*/
|
|
56
|
+
export type MoneyFormatPart = {
|
|
57
|
+
type: 'currency' | 'decimal' | 'fraction' | 'integer' | 'literal' | 'minusSign';
|
|
58
|
+
value: string;
|
|
59
|
+
};
|
|
60
|
+
//# sourceMappingURL=types.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"types.d.ts","sourceRoot":"","sources":["../src/types.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AACH,MAAM,MAAM,YAAY,GAAG,MAAM,CAAC;AAElC,uFAAuF;AACvF,MAAM,MAAM,KAAK,GAAG;IAClB,QAAQ,CAAC,MAAM,EAAE,MAAM,CAAC;IACxB,QAAQ,CAAC,QAAQ,EAAE,YAAY,CAAC;CACjC,CAAC;AAEF;;;;;;;;;GASG;AACH,MAAM,MAAM,YAAY,GAAG;IACzB,QAAQ,CAAC,IAAI,EAAE,YAAY,CAAC;IAC5B,QAAQ,CAAC,IAAI,EAAE,MAAM,GAAG,MAAM,CAAC;IAC/B,QAAQ,CAAC,EAAE,EAAE,YAAY,CAAC;CAC3B,CAAC;AAEF,8BAA8B;AAC9B,MAAM,MAAM,aAAa,GAAG;IAC1B,MAAM,CAAC,EAAE,MAAM,CAAC;IAChB,qBAAqB,CAAC,EAAE,MAAM,CAAC;IAC/B,qBAAqB,CAAC,EAAE,MAAM,CAAC;IAC/B,KAAK,CAAC,EAAE,MAAM,GAAG,MAAM,GAAG,cAAc,GAAG,QAAQ,CAAC;CACrD,CAAC;AAEF;;;;;;;;;;;GAWG;AACH,MAAM,MAAM,YAAY,GAAG,SAAS,GAAG,MAAM,GAAG,OAAO,GAAG,qBAAqB,GAAG,WAAW,GAAG,IAAI,CAAC;AAErG,sHAAsH;AACtH,MAAM,MAAM,SAAS,GAAG;IACtB,MAAM,EAAE,MAAM,CAAC;IACf,QAAQ,EAAE,MAAM,CAAC;CAClB,CAAC;AAEF;;;GAGG;AACH,MAAM,MAAM,eAAe,GAAG;IAC5B,IAAI,EAAE,UAAU,GAAG,SAAS,GAAG,UAAU,GAAG,SAAS,GAAG,SAAS,GAAG,WAAW,CAAC;IAChF,KAAK,EAAE,MAAM,CAAC;CACf,CAAC"}
|
package/dist/utils.cjs
ADDED
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
const e=require("./errors.cjs");var t=require("./_cache.cjs").boundedCache(512);function n(n){let r=t.get(n);if(r!==void 0)return r;let i;try{i=new Intl.NumberFormat(`en`,{currency:n,style:`currency`}).resolvedOptions().maximumFractionDigits}catch{throw new e.InvalidCurrencyError(n)}if(i===void 0)throw new e.InvalidCurrencyError(n);return t.set(n,i),i}function r(e){return n(e),e}function i(e){return 10n**BigInt(e)}var a=/^-?\d+(\.\d+)?$/,o=/^(-?\d+\.?\d*)[eE]([+-]?\d+)$/,s=1e3;function c(t){let n=o.exec(t),r=n[1],i=parseInt(n[2],10);if(Math.abs(i)>s)throw new e.CoinsError(`Scientific notation exponent too large: "${t}" (max ±${s})`);let a=r.startsWith(`-`),c=a?r.slice(1):r,l=c.indexOf(`.`),u=l===-1?c:c.replace(`.`,``),d=i-(l===-1?0:c.length-l-1),f;if(d>=0)f=u+`0`.repeat(d);else{let e=u.length+d;f=e<=0?`0.`+`0`.repeat(-e)+u:u.slice(0,e)+`.`+u.slice(e)}return a?`-${f}`:f}function l(t){let n=o.test(t)?c(t):t;if(!a.test(n))throw new e.CoinsError(`Invalid decimal string: "${t}"`);let r=n.startsWith(`-`),s=r?n.slice(1):n,l=s.indexOf(`.`),u=l===-1?s:s.slice(0,l),d=l===-1?``:s.slice(l+1),f=i(d.length);return{denominator:f,negative:r,numerator:BigInt(u||`0`)*f+BigInt(d||`0`)}}function u(t,n,r,i,a=!1){if(n===0n)return t;switch(i){case`ceiling`:return a?t:t+1n;case`down`:return t;case`floor`:return a?t+1n:t;case`half-away-from-zero`:return n*2n>=r?t+1n:t;case`half-even`:{let e=n*2n;return e<r?t:e>r?t+1n:t%2n==0n?t:t+1n}case`up`:return t+1n;default:throw new e.CoinsError(`Unknown rounding mode: ${String(i)}`)}}exports.SCIENTIFIC_RE=o,exports.applyRounding=u,exports.expandScientific=c,exports.getCurrencyDecimals=n,exports.parseRational=l,exports.pow10=i,exports.validateCurrencyCode=r;
|
|
2
|
+
//# sourceMappingURL=utils.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"utils.cjs","names":[],"sources":["../src/utils.ts"],"sourcesContent":["import type { CurrencyCode, RoundingMode } from './types';\n\nimport { boundedCache } from './_cache';\nimport { CoinsError, InvalidCurrencyError } from './errors';\n\nconst currencyDecimalsCache = boundedCache<string, number>(512);\n\n/**\n * Returns the number of minor-unit decimal places for a given ISO 4217 currency code.\n * Uses `Intl.NumberFormat` to resolve the canonical value (e.g. USD→2, JPY→0, KWD→3).\n * Throws `InvalidCurrencyError` for unrecognized codes or when the runtime cannot determine decimals.\n */\nexport function getCurrencyDecimals(currencyCode: CurrencyCode): number {\n const cached = currencyDecimalsCache.get(currencyCode);\n\n if (cached !== undefined) return cached;\n\n let resolved: number | undefined;\n\n try {\n resolved = new Intl.NumberFormat('en', { currency: currencyCode, style: 'currency' }).resolvedOptions()\n .maximumFractionDigits;\n } catch {\n throw new InvalidCurrencyError(currencyCode);\n }\n\n if (resolved === undefined) {\n throw new InvalidCurrencyError(currencyCode);\n }\n\n currencyDecimalsCache.set(currencyCode, resolved);\n\n return resolved;\n}\n\n/**\n * Validates an ISO 4217 currency code and returns it.\n * Throws `InvalidCurrencyError` if unrecognized. Uses `getCurrencyDecimals` internally so\n * the result is cached for subsequent decimal lookups.\n */\nexport function validateCurrencyCode(code: CurrencyCode): CurrencyCode {\n getCurrencyDecimals(code);\n\n return code;\n}\n\n/** Returns `10n ** BigInt(exponent)`. */\nexport function pow10(exponent: number): bigint {\n return 10n ** BigInt(exponent);\n}\n\n/** Regex for valid decimal strings accepted by `parseRational`. */\nconst DECIMAL_RE = /^-?\\d+(\\.\\d+)?$/;\n\n/** Regex matching JavaScript scientific-notation strings, e.g. `'1e-7'`, `'-3.14E+5'`. */\nexport const SCIENTIFIC_RE = /^(-?\\d+\\.?\\d*)[eE]([+-]?\\d+)$/;\n\n/** Maximum absolute exponent allowed in scientific notation. Prevents '0'.repeat(N) allocation attacks. */\nconst MAX_SCIENTIFIC_EXP = 1000;\n\n/**\n * Expands a scientific-notation decimal string into a plain decimal string.\n * `'1e-7'` → `'0.0000001'`, `'1.23e+5'` → `'123000'`.\n * Only called when `SCIENTIFIC_RE` already matched — no extra validation.\n * @throws {CoinsError} If the absolute exponent exceeds `MAX_SCIENTIFIC_EXP` (1000).\n */\nexport function expandScientific(s: string): string {\n const match = SCIENTIFIC_RE.exec(s)!;\n const coeff = match[1]!;\n const exp = parseInt(match[2]!, 10);\n\n if (Math.abs(exp) > MAX_SCIENTIFIC_EXP) {\n throw new CoinsError(`Scientific notation exponent too large: \"${s}\" (max ±${MAX_SCIENTIFIC_EXP})`);\n }\n\n const isNeg = coeff.startsWith('-');\n const absCoeff = isNeg ? coeff.slice(1) : coeff;\n const dotIndex = absCoeff.indexOf('.');\n const digits = dotIndex === -1 ? absCoeff : absCoeff.replace('.', '');\n const fracLen = dotIndex === -1 ? 0 : absCoeff.length - dotIndex - 1;\n const newExp = exp - fracLen; // where the decimal point sits relative to end of digits\n\n let result: string;\n\n if (newExp >= 0) {\n // All digits are to the left of the decimal — append trailing zeros\n result = digits + '0'.repeat(newExp);\n } else {\n const intLen = digits.length + newExp; // digits before the decimal point\n\n if (intLen <= 0) {\n // Pure fraction: '0.' + leading zeros + digits\n result = '0.' + '0'.repeat(-intLen) + digits;\n } else {\n result = digits.slice(0, intLen) + '.' + digits.slice(intLen);\n }\n }\n\n return isNeg ? `-${result}` : result;\n}\n\n/**\n * Parses a decimal string into a rational `{ numerator, denominator, negative }`.\n * The denominator is always a power of 10 and the numerator is always non-negative.\n * @throws {CoinsError} For non-numeric input.\n *\n * Accepts standard decimal strings and JavaScript scientific notation\n * (e.g. `'1e-7'`, `'1.23E+5'`) — the latter is automatically expanded before parsing.\n *\n * @example\n * parseRational('1.5') → { numerator: 15n, denominator: 10n, negative: false }\n * parseRational('-0.5') → { numerator: 5n, denominator: 10n, negative: true }\n * parseRational('3') → { numerator: 3n, denominator: 1n, negative: false }\n * parseRational('1e-7') → { numerator: 1n, denominator: 10000000n, negative: false }\n *\n * Note: `'-0'` and `'-0.0'` produce `{ negative: true, numerator: 0n, ... }`.\n * Callers that compute `negative ? -result : result` on `0n` remain correct\n * because `-0n === 0n` in bigint arithmetic.\n */\nexport function parseRational(str: string): { denominator: bigint; negative: boolean; numerator: bigint } {\n // Expand scientific notation (e.g. from String(1e-7) = '1e-7') before validation.\n const normalized = SCIENTIFIC_RE.test(str) ? expandScientific(str) : str;\n\n if (!DECIMAL_RE.test(normalized)) {\n throw new CoinsError(`Invalid decimal string: \"${str}\"`);\n }\n\n const negative = normalized.startsWith('-');\n const absStr = negative ? normalized.slice(1) : normalized;\n const dotIndex = absStr.indexOf('.');\n const intStr = dotIndex === -1 ? absStr : absStr.slice(0, dotIndex);\n const fracStr = dotIndex === -1 ? '' : absStr.slice(dotIndex + 1);\n const denominator = pow10(fracStr.length);\n const numerator = BigInt(intStr || '0') * denominator + BigInt(fracStr || '0');\n\n return { denominator, negative, numerator };\n}\n\n/**\n * Applies a rounding mode to a truncated division result.\n *\n * **Contract**: `quotient` and `absRemainder` must be non-negative (absolute values).\n * The caller is responsible for:\n * 1. Computing everything in terms of absolute values.\n * 2. Passing `negative = true` when the true mathematical result is negative.\n * 3. Applying the sign after: `negative ? -result : result`.\n *\n * Returns the absolute value of the rounded result.\n *\n * @param quotient Non-negative integer part of the division (`|dividend| / divisor`).\n * @param absRemainder Non-negative remainder (`|dividend| % divisor`).\n * @param denominator The divisor used to produce quotient/remainder.\n * @param mode The desired rounding mode.\n * @param negative Whether the true mathematical result is negative. Defaults to `false`.\n */\nexport function applyRounding(\n quotient: bigint,\n absRemainder: bigint,\n denominator: bigint,\n mode: RoundingMode,\n negative = false,\n): bigint {\n if (absRemainder === 0n) return quotient;\n\n switch (mode) {\n case 'ceiling':\n // Toward +∞: round up for positive results, truncate for negative results.\n return negative ? quotient : quotient + 1n;\n\n case 'down':\n // Toward zero: always truncate.\n return quotient;\n\n case 'floor':\n // Toward −∞: truncate for positive results, one step more for negative results.\n return negative ? quotient + 1n : quotient;\n\n case 'half-away-from-zero':\n return absRemainder * 2n >= denominator ? quotient + 1n : quotient;\n\n case 'half-even': {\n const twice = absRemainder * 2n;\n\n if (twice < denominator) return quotient;\n\n if (twice > denominator) return quotient + 1n;\n\n // Exactly half — round to the nearest even integer.\n return quotient % 2n === 0n ? quotient : quotient + 1n;\n }\n\n case 'up':\n // Away from zero: always round away.\n return quotient + 1n;\n\n default:\n throw new CoinsError(`Unknown rounding mode: ${String(mode)}`);\n }\n}\n"],"mappings":"gCAKA,IAAM,wBAAwB,CAAA,CAAA,aAA6B,GAAG,EAO9D,SAAgB,EAAoB,EAAoC,CACtE,IAAM,EAAS,EAAsB,IAAI,CAAY,EAErD,GAAI,IAAW,IAAA,GAAW,OAAO,EAEjC,IAAI,EAEJ,GAAI,CACF,EAAW,IAAI,KAAK,aAAa,KAAM,CAAE,SAAU,EAAc,MAAO,UAAW,CAAC,CAAC,CAAC,gBAAgB,CAAC,CACpG,qBACL,MAAQ,CACN,MAAM,IAAI,EAAA,qBAAqB,CAAY,CAC7C,CAEA,GAAI,IAAa,IAAA,GACf,MAAM,IAAI,EAAA,qBAAqB,CAAY,EAK7C,OAFA,EAAsB,IAAI,EAAc,CAAQ,EAEzC,CACT,CAOA,SAAgB,EAAqB,EAAkC,CAGrE,OAFA,EAAoB,CAAI,EAEjB,CACT,CAGA,SAAgB,EAAM,EAA0B,CAC9C,OAAO,KAAO,OAAO,CAAQ,CAC/B,CAGA,IAAM,EAAa,kBAGN,EAAgB,gCAGvB,EAAqB,IAQ3B,SAAgB,EAAiB,EAAmB,CAClD,IAAM,EAAQ,EAAc,KAAK,CAAC,EAC5B,EAAQ,EAAM,GACd,EAAM,SAAS,EAAM,GAAK,EAAE,EAElC,GAAI,KAAK,IAAI,CAAG,EAAI,EAClB,MAAM,IAAI,EAAA,WAAW,4CAA4C,EAAE,UAAU,EAAmB,EAAE,EAGpG,IAAM,EAAQ,EAAM,WAAW,GAAG,EAC5B,EAAW,EAAQ,EAAM,MAAM,CAAC,EAAI,EACpC,EAAW,EAAS,QAAQ,GAAG,EAC/B,EAAS,IAAa,GAAK,EAAW,EAAS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oB,EAAW,GAGpC,EAAW,IAAO,GAAK,EAAW,EAAW,EACtD,CAEA,IAAK,KAEH,OAAO,EAAW,GAEpB,QACE,MAAM,IAAI,EAAA,WAAW,0BAA0B,OAAO,CAAI,GAAG,CACjE,CACF"}
|
package/dist/utils.d.ts
ADDED
|
@@ -0,0 +1,66 @@
|
|
|
1
|
+
import type { CurrencyCode, RoundingMode } from './types';
|
|
2
|
+
/**
|
|
3
|
+
* Returns the number of minor-unit decimal places for a given ISO 4217 currency code.
|
|
4
|
+
* Uses `Intl.NumberFormat` to resolve the canonical value (e.g. USD→2, JPY→0, KWD→3).
|
|
5
|
+
* Throws `InvalidCurrencyError` for unrecognized codes or when the runtime cannot determine decimals.
|
|
6
|
+
*/
|
|
7
|
+
export declare function getCurrencyDecimals(currencyCode: CurrencyCode): number;
|
|
8
|
+
/**
|
|
9
|
+
* Validates an ISO 4217 currency code and returns it.
|
|
10
|
+
* Throws `InvalidCurrencyError` if unrecognized. Uses `getCurrencyDecimals` internally so
|
|
11
|
+
* the result is cached for subsequent decimal lookups.
|
|
12
|
+
*/
|
|
13
|
+
export declare function validateCurrencyCode(code: CurrencyCode): CurrencyCode;
|
|
14
|
+
/** Returns `10n ** BigInt(exponent)`. */
|
|
15
|
+
export declare function pow10(exponent: number): bigint;
|
|
16
|
+
/** Regex matching JavaScript scientific-notation strings, e.g. `'1e-7'`, `'-3.14E+5'`. */
|
|
17
|
+
export declare const SCIENTIFIC_RE: RegExp;
|
|
18
|
+
/**
|
|
19
|
+
* Expands a scientific-notation decimal string into a plain decimal string.
|
|
20
|
+
* `'1e-7'` → `'0.0000001'`, `'1.23e+5'` → `'123000'`.
|
|
21
|
+
* Only called when `SCIENTIFIC_RE` already matched — no extra validation.
|
|
22
|
+
* @throws {CoinsError} If the absolute exponent exceeds `MAX_SCIENTIFIC_EXP` (1000).
|
|
23
|
+
*/
|
|
24
|
+
export declare function expandScientific(s: string): string;
|
|
25
|
+
/**
|
|
26
|
+
* Parses a decimal string into a rational `{ numerator, denominator, negative }`.
|
|
27
|
+
* The denominator is always a power of 10 and the numerator is always non-negative.
|
|
28
|
+
* @throws {CoinsError} For non-numeric input.
|
|
29
|
+
*
|
|
30
|
+
* Accepts standard decimal strings and JavaScript scientific notation
|
|
31
|
+
* (e.g. `'1e-7'`, `'1.23E+5'`) — the latter is automatically expanded before parsing.
|
|
32
|
+
*
|
|
33
|
+
* @example
|
|
34
|
+
* parseRational('1.5') → { numerator: 15n, denominator: 10n, negative: false }
|
|
35
|
+
* parseRational('-0.5') → { numerator: 5n, denominator: 10n, negative: true }
|
|
36
|
+
* parseRational('3') → { numerator: 3n, denominator: 1n, negative: false }
|
|
37
|
+
* parseRational('1e-7') → { numerator: 1n, denominator: 10000000n, negative: false }
|
|
38
|
+
*
|
|
39
|
+
* Note: `'-0'` and `'-0.0'` produce `{ negative: true, numerator: 0n, ... }`.
|
|
40
|
+
* Callers that compute `negative ? -result : result` on `0n` remain correct
|
|
41
|
+
* because `-0n === 0n` in bigint arithmetic.
|
|
42
|
+
*/
|
|
43
|
+
export declare function parseRational(str: string): {
|
|
44
|
+
denominator: bigint;
|
|
45
|
+
negative: boolean;
|
|
46
|
+
numerator: bigint;
|
|
47
|
+
};
|
|
48
|
+
/**
|
|
49
|
+
* Applies a rounding mode to a truncated division result.
|
|
50
|
+
*
|
|
51
|
+
* **Contract**: `quotient` and `absRemainder` must be non-negative (absolute values).
|
|
52
|
+
* The caller is responsible for:
|
|
53
|
+
* 1. Computing everything in terms of absolute values.
|
|
54
|
+
* 2. Passing `negative = true` when the true mathematical result is negative.
|
|
55
|
+
* 3. Applying the sign after: `negative ? -result : result`.
|
|
56
|
+
*
|
|
57
|
+
* Returns the absolute value of the rounded result.
|
|
58
|
+
*
|
|
59
|
+
* @param quotient Non-negative integer part of the division (`|dividend| / divisor`).
|
|
60
|
+
* @param absRemainder Non-negative remainder (`|dividend| % divisor`).
|
|
61
|
+
* @param denominator The divisor used to produce quotient/remainder.
|
|
62
|
+
* @param mode The desired rounding mode.
|
|
63
|
+
* @param negative Whether the true mathematical result is negative. Defaults to `false`.
|
|
64
|
+
*/
|
|
65
|
+
export declare function applyRounding(quotient: bigint, absRemainder: bigint, denominator: bigint, mode: RoundingMode, negative?: boolean): bigint;
|
|
66
|
+
//# sourceMappingURL=utils.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"utils.d.ts","sourceRoot":"","sources":["../src/utils.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,YAAY,EAAE,YAAY,EAAE,MAAM,SAAS,CAAC;AAO1D;;;;GAIG;AACH,wBAAgB,mBAAmB,CAAC,YAAY,EAAE,YAAY,GAAG,MAAM,CAqBtE;AAED;;;;GAIG;AACH,wBAAgB,oBAAoB,CAAC,IAAI,EAAE,YAAY,GAAG,YAAY,CAIrE;AAED,yCAAyC;AACzC,wBAAgB,KAAK,CAAC,QAAQ,EAAE,MAAM,GAAG,MAAM,CAE9C;AAKD,0FAA0F;AAC1F,eAAO,MAAM,aAAa,QAAkC,CAAC;AAK7D;;;;;GAKG;AACH,wBAAgB,gBAAgB,CAAC,CAAC,EAAE,MAAM,GAAG,MAAM,CAiClD;AAED;;;;;;;;;;;;;;;;;GAiBG;AACH,wBAAgB,aAAa,CAAC,GAAG,EAAE,MAAM,GAAG;IAAE,WAAW,EAAE,MAAM,CAAC;IAAC,QAAQ,EAAE,OAAO,CAAC;IAAC,SAAS,EAAE,MAAM,CAAA;CAAE,CAiBxG;AAED;;;;;;;;;;;;;;;;GAgBG;AACH,wBAAgB,aAAa,CAC3B,QAAQ,EAAE,MAAM,EAChB,YAAY,EAAE,MAAM,EACpB,WAAW,EAAE,MAAM,EACnB,IAAI,EAAE,YAAY,EAClB,QAAQ,UAAQ,GACf,MAAM,CAqCR"}
|
package/dist/utils.js
ADDED
|
@@ -0,0 +1,66 @@
|
|
|
1
|
+
import { CoinsError as e, InvalidCurrencyError as t } from "./errors.js";
|
|
2
|
+
import { boundedCache as n } from "./_cache.js";
|
|
3
|
+
//#region src/utils.ts
|
|
4
|
+
var r = n(512);
|
|
5
|
+
function i(e) {
|
|
6
|
+
let n = r.get(e);
|
|
7
|
+
if (n !== void 0) return n;
|
|
8
|
+
let i;
|
|
9
|
+
try {
|
|
10
|
+
i = new Intl.NumberFormat("en", {
|
|
11
|
+
currency: e,
|
|
12
|
+
style: "currency"
|
|
13
|
+
}).resolvedOptions().maximumFractionDigits;
|
|
14
|
+
} catch {
|
|
15
|
+
throw new t(e);
|
|
16
|
+
}
|
|
17
|
+
if (i === void 0) throw new t(e);
|
|
18
|
+
return r.set(e, i), i;
|
|
19
|
+
}
|
|
20
|
+
function a(e) {
|
|
21
|
+
return i(e), e;
|
|
22
|
+
}
|
|
23
|
+
function o(e) {
|
|
24
|
+
return 10n ** BigInt(e);
|
|
25
|
+
}
|
|
26
|
+
var s = /^-?\d+(\.\d+)?$/, c = /^(-?\d+\.?\d*)[eE]([+-]?\d+)$/, l = 1e3;
|
|
27
|
+
function u(t) {
|
|
28
|
+
let n = c.exec(t), r = n[1], i = parseInt(n[2], 10);
|
|
29
|
+
if (Math.abs(i) > l) throw new e(`Scientific notation exponent too large: "${t}" (max ±${l})`);
|
|
30
|
+
let a = r.startsWith("-"), o = a ? r.slice(1) : r, s = o.indexOf("."), u = s === -1 ? o : o.replace(".", ""), d = i - (s === -1 ? 0 : o.length - s - 1), f;
|
|
31
|
+
if (d >= 0) f = u + "0".repeat(d);
|
|
32
|
+
else {
|
|
33
|
+
let e = u.length + d;
|
|
34
|
+
f = e <= 0 ? "0." + "0".repeat(-e) + u : u.slice(0, e) + "." + u.slice(e);
|
|
35
|
+
}
|
|
36
|
+
return a ? `-${f}` : f;
|
|
37
|
+
}
|
|
38
|
+
function d(t) {
|
|
39
|
+
let n = c.test(t) ? u(t) : t;
|
|
40
|
+
if (!s.test(n)) throw new e(`Invalid decimal string: "${t}"`);
|
|
41
|
+
let r = n.startsWith("-"), i = r ? n.slice(1) : n, a = i.indexOf("."), l = a === -1 ? i : i.slice(0, a), d = a === -1 ? "" : i.slice(a + 1), f = o(d.length);
|
|
42
|
+
return {
|
|
43
|
+
denominator: f,
|
|
44
|
+
negative: r,
|
|
45
|
+
numerator: BigInt(l || "0") * f + BigInt(d || "0")
|
|
46
|
+
};
|
|
47
|
+
}
|
|
48
|
+
function f(t, n, r, i, a = !1) {
|
|
49
|
+
if (n === 0n) return t;
|
|
50
|
+
switch (i) {
|
|
51
|
+
case "ceiling": return a ? t : t + 1n;
|
|
52
|
+
case "down": return t;
|
|
53
|
+
case "floor": return a ? t + 1n : t;
|
|
54
|
+
case "half-away-from-zero": return n * 2n >= r ? t + 1n : t;
|
|
55
|
+
case "half-even": {
|
|
56
|
+
let e = n * 2n;
|
|
57
|
+
return e < r ? t : e > r ? t + 1n : t % 2n == 0n ? t : t + 1n;
|
|
58
|
+
}
|
|
59
|
+
case "up": return t + 1n;
|
|
60
|
+
default: throw new e(`Unknown rounding mode: ${String(i)}`);
|
|
61
|
+
}
|
|
62
|
+
}
|
|
63
|
+
//#endregion
|
|
64
|
+
export { c as SCIENTIFIC_RE, f as applyRounding, u as expandScientific, i as getCurrencyDecimals, d as parseRational, o as pow10, a as validateCurrencyCode };
|
|
65
|
+
|
|
66
|
+
//# sourceMappingURL=utils.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"utils.js","names":[],"sources":["../src/utils.ts"],"sourcesContent":["import type { CurrencyCode, RoundingMode } from './types';\n\nimport { boundedCache } from './_cache';\nimport { CoinsError, InvalidCurrencyError } from './errors';\n\nconst currencyDecimalsCache = boundedCache<string, number>(512);\n\n/**\n * Returns the number of minor-unit decimal places for a given ISO 4217 currency code.\n * Uses `Intl.NumberFormat` to resolve the canonical value (e.g. USD→2, JPY→0, KWD→3).\n * Throws `InvalidCurrencyError` for unrecognized codes or when the runtime cannot determine decimals.\n */\nexport function getCurrencyDecimals(currencyCode: CurrencyCode): number {\n const cached = currencyDecimalsCache.get(currencyCode);\n\n if (cached !== undefined) return cached;\n\n let resolved: number | undefined;\n\n try {\n resolved = new Intl.NumberFormat('en', { currency: currencyCode, style: 'currency' }).resolvedOptions()\n .maximumFractionDigits;\n } catch {\n throw new InvalidCurrencyError(currencyCode);\n }\n\n if (resolved === undefined) {\n throw new InvalidCurrencyError(currencyCode);\n }\n\n currencyDecimalsCache.set(currencyCode, resolved);\n\n return resolved;\n}\n\n/**\n * Validates an ISO 4217 currency code and returns it.\n * Throws `InvalidCurrencyError` if unrecognized. Uses `getCurrencyDecimals` internally so\n * the result is cached for subsequent decimal lookups.\n */\nexport function validateCurrencyCode(code: CurrencyCode): CurrencyCode {\n getCurrencyDecimals(code);\n\n return code;\n}\n\n/** Returns `10n ** BigInt(exponent)`. */\nexport function pow10(exponent: number): bigint {\n return 10n ** BigInt(exponent);\n}\n\n/** Regex for valid decimal strings accepted by `parseRational`. */\nconst DECIMAL_RE = /^-?\\d+(\\.\\d+)?$/;\n\n/** Regex matching JavaScript scientific-notation strings, e.g. `'1e-7'`, `'-3.14E+5'`. */\nexport const SCIENTIFIC_RE = /^(-?\\d+\\.?\\d*)[eE]([+-]?\\d+)$/;\n\n/** Maximum absolute exponent allowed in scientific notation. Prevents '0'.repeat(N) allocation attacks. */\nconst MAX_SCIENTIFIC_EXP = 1000;\n\n/**\n * Expands a scientific-notation decimal string into a plain decimal string.\n * `'1e-7'` → `'0.0000001'`, `'1.23e+5'` → `'123000'`.\n * Only called when `SCIENTIFIC_RE` already matched — no extra validation.\n * @throws {CoinsError} If the absolute exponent exceeds `MAX_SCIENTIFIC_EXP` (1000).\n */\nexport function expandScientific(s: string): string {\n const match = SCIENTIFIC_RE.exec(s)!;\n const coeff = match[1]!;\n const exp = parseInt(match[2]!, 10);\n\n if (Math.abs(exp) > MAX_SCIENTIFIC_EXP) {\n throw new CoinsError(`Scientific notation exponent too large: \"${s}\" (max ±${MAX_SCIENTIFIC_EXP})`);\n }\n\n const isNeg = coeff.startsWith('-');\n const absCoeff = isNeg ? coeff.slice(1) : coeff;\n const dotIndex = absCoeff.indexOf('.');\n const digits = dotIndex === -1 ? absCoeff : absCoeff.replace('.', '');\n const fracLen = dotIndex === -1 ? 0 : absCoeff.length - dotIndex - 1;\n const newExp = exp - fracLen; // where the decimal point sits relative to end of digits\n\n let result: string;\n\n if (newExp >= 0) {\n // All digits are to the left of the decimal — append trailing zeros\n result = digits + '0'.repeat(newExp);\n } else {\n const intLen = digits.length + newExp; // digits before the decimal point\n\n if (intLen <= 0) {\n // Pure fraction: '0.' + leading zeros + digits\n result = '0.' + '0'.repeat(-intLen) + digits;\n } else {\n result = digits.slice(0, intLen) + '.' + digits.slice(intLen);\n }\n }\n\n return isNeg ? `-${result}` : result;\n}\n\n/**\n * Parses a decimal string into a rational `{ numerator, denominator, negative }`.\n * The denominator is always a power of 10 and the numerator is always non-negative.\n * @throws {CoinsError} For non-numeric input.\n *\n * Accepts standard decimal strings and JavaScript scientific notation\n * (e.g. `'1e-7'`, `'1.23E+5'`) — the latter is automatically expanded before parsing.\n *\n * @example\n * parseRational('1.5') → { numerator: 15n, denominator: 10n, negative: false }\n * parseRational('-0.5') → { numerator: 5n, denominator: 10n, negative: true }\n * parseRational('3') → { numerator: 3n, denominator: 1n, negative: false }\n * parseRational('1e-7') → { numerator: 1n, denominator: 10000000n, negative: false }\n *\n * Note: `'-0'` and `'-0.0'` produce `{ negative: true, numerator: 0n, ... }`.\n * Callers that compute `negative ? -result : result` on `0n` remain correct\n * because `-0n === 0n` in bigint arithmetic.\n */\nexport function parseRational(str: string): { denominator: bigint; negative: boolean; numerator: bigint } {\n // Expand scientific notation (e.g. from String(1e-7) = '1e-7') before validation.\n const normalized = SCIENTIFIC_RE.test(str) ? expandScientific(str) : str;\n\n if (!DECIMAL_RE.test(normalized)) {\n throw new CoinsError(`Invalid decimal string: \"${str}\"`);\n }\n\n const negative = normalized.startsWith('-');\n const absStr = negative ? normalized.slice(1) : normalized;\n const dotIndex = absStr.indexOf('.');\n const intStr = dotIndex === -1 ? absStr : absStr.slice(0, dotIndex);\n const fracStr = dotIndex === -1 ? '' : absStr.slice(dotIndex + 1);\n const denominator = pow10(fracStr.length);\n const numerator = BigInt(intStr || '0') * denominator + BigInt(fracStr || '0');\n\n return { denominator, negative, numerator };\n}\n\n/**\n * Applies a rounding mode to a truncated division result.\n *\n * **Contract**: `quotient` and `absRemainder` must be non-negative (absolute values).\n * The caller is responsible for:\n * 1. Computing everything in terms of absolute values.\n * 2. Passing `negative = true` when the true mathematical result is negative.\n * 3. Applying the sign after: `negative ? -result : result`.\n *\n * Returns the absolute value of the rounded result.\n *\n * @param quotient Non-negative integer part of the division (`|dividend| / divisor`).\n * @param absRemainder Non-negative remainder (`|dividend| % divisor`).\n * @param denominator The divisor used to produce quotient/remainder.\n * @param mode The desired rounding mode.\n * @param negative Whether the true mathematical result is negative. Defaults to `false`.\n */\nexport function applyRounding(\n quotient: bigint,\n absRemainder: bigint,\n denominator: bigint,\n mode: RoundingMode,\n negative = false,\n): bigint {\n if (absRemainder === 0n) return quotient;\n\n switch (mode) {\n case 'ceiling':\n // Toward +∞: round up for positive results, truncate for negative results.\n return negative ? quotient : quotient + 1n;\n\n case 'down':\n // Toward zero: always truncate.\n return quotient;\n\n case 'floor':\n // Toward −∞: truncate for positive results, one step more for negative results.\n return negative ? quotient + 1n : quotient;\n\n case 'half-away-from-zero':\n return absRemainder * 2n >= denominator ? quotient + 1n : quotient;\n\n case 'half-even': {\n const twice = absRemainder * 2n;\n\n if (twice < denominator) return quotient;\n\n if (twice > denominator) return quotient + 1n;\n\n // Exactly half — round to the nearest even integer.\n return quotient % 2n === 0n ? quotient : quotient + 1n;\n }\n\n case 'up':\n // Away from zero: always round away.\n return quotient + 1n;\n\n default:\n throw new CoinsError(`Unknown rounding mode: ${String(mode)}`);\n }\n}\n"],"mappings":";;;AAKA,IAAM,IAAwB,EAA6B,GAAG;AAO9D,SAAgB,EAAoB,GAAoC;CACtE,IAAM,IAAS,EAAsB,IAAI,CAAY;CAErD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GAA4E;CAExG,IAAM,IAAa,EAAc,KAAK,CAAG,IAAI,EAAiB,CAAG,IAAI;CAErE,IAAI,CAAC,EAAW,KAAK,CAAU,GAC7B,MAAM,IAAI,EAAW,4BAA4B,EAAI,EAAE;CAGzD,IAAM,IAAW,EAAW,WAAW,GAAG,GACpC,IAAS,IAAW,EAAW,MAAM,CAAC,IAAI,GAC1C,IAAW,EAAO,QAAQ,GAAG,GAC7B,IAAS,MAAa,KAAK,IAAS,EAAO,MAAM,GAAG,CAAQ,GAC5D,IAAU,MAAa,KAAK,KAAK,EAAO,MAAM,IAAW,CAAC,GAC1D,IAAc,EAAM,EAAQ,MAAM;CAGxC,OAAO;EAAE;EAAa;EAAU,WAFd,OAAO,KAAU,GAAG,IAAI,IAAc,OAAO,KAAW,GAAG;CAEnC;AAC5C;AAmBA,SAAgB,EACd,GACA,GACA,GACA,GACA,IAAW,IACH;CACR,IAAI,MAAiB,IAAI,OAAO;CAEhC,QAAQ,GAAR;EACE,KAAK,WAEH,OAAO,IAAW,IAAW,IAAW;EAE1C,KAAK,QAEH,OAAO;EAET,KAAK,SAEH,OAAO,IAAW,IAAW,KAAK;EAEpC,KAAK,uBACH,OAAO,IAAe,MAAM,IAAc,IAAW,KAAK;EAE5D,KAAK,aAAa;GAChB,IAAM,IAAQ,IAAe;GAO7B,OALI,IAAQ,IAAoB,IAE5B,IAAQ,IAAoB,IAAW,KAGpC,IAAW,MAAO,KAAK,IAAW,IAAW;EACtD;EAEA,KAAK,MAEH,OAAO,IAAW;EAEpB,SACE,MAAM,IAAI,EAAW,0BAA0B,OAAO,CAAI,GAAG;CACjE;AACF"}
|
package/package.json
ADDED
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "@vielzeug/coins",
|
|
3
|
+
"version": "1.0.2",
|
|
4
|
+
"description": "Bigint-based monetary arithmetic with currency formatting, exchange rates, and rounding policies",
|
|
5
|
+
"type": "module",
|
|
6
|
+
"files": [
|
|
7
|
+
"dist"
|
|
8
|
+
],
|
|
9
|
+
"main": "./dist/index.cjs",
|
|
10
|
+
"module": "./dist/index.js",
|
|
11
|
+
"types": "dist/index.d.ts",
|
|
12
|
+
"exports": {
|
|
13
|
+
".": {
|
|
14
|
+
"source": "./src/index.ts",
|
|
15
|
+
"types": "./dist/index.d.ts",
|
|
16
|
+
"import": "./dist/index.js",
|
|
17
|
+
"require": "./dist/index.cjs"
|
|
18
|
+
}
|
|
19
|
+
},
|
|
20
|
+
"scripts": {
|
|
21
|
+
"build": "vite build && pnpm run build:bundle && pnpm run build:types",
|
|
22
|
+
"build:types": "tsc -p tsconfig.declarations.json",
|
|
23
|
+
"fix": "eslint --fix src",
|
|
24
|
+
"lint": "eslint src",
|
|
25
|
+
"prepublishOnly": "pnpm run build",
|
|
26
|
+
"test": "vitest",
|
|
27
|
+
"build:bundle": "vite build --config vite.bundle.config.ts"
|
|
28
|
+
},
|
|
29
|
+
"publishConfig": {
|
|
30
|
+
"access": "public",
|
|
31
|
+
"registry": "https://registry.npmjs.org/"
|
|
32
|
+
},
|
|
33
|
+
"devDependencies": {
|
|
34
|
+
"@types/node": "^26.1.0",
|
|
35
|
+
"typescript": "~6.0.3",
|
|
36
|
+
"vite": "^8.1.3",
|
|
37
|
+
"vitest": "^4.1.9"
|
|
38
|
+
}
|
|
39
|
+
}
|