@ducatjs/money 0.0.0 → 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/NOTICE +51 -0
- package/README.md +617 -3
- package/assets/CREDITS.md +12 -0
- package/data/adyen-fx.json +19 -0
- package/data/adyen.json +171 -0
- package/data/braintree.json +223 -0
- package/data/cash-rounding.json +399 -0
- package/data/checkout.json +230 -0
- package/data/iso4217-list-one.xml +1956 -0
- package/data/klarna.json +95 -0
- package/data/paypal.json +65 -0
- package/data/stripe-fx.json +17 -0
- package/data/stripe.json +285 -0
- package/dist/adyen-fx.d.ts +25 -0
- package/dist/adyen-fx.d.ts.map +1 -0
- package/dist/adyen-fx.js +122 -0
- package/dist/adyen-fx.js.map +1 -0
- package/dist/adyen.d.ts +25 -0
- package/dist/adyen.d.ts.map +1 -0
- package/dist/adyen.js +34 -0
- package/dist/adyen.js.map +1 -0
- package/dist/allocate.d.ts +72 -0
- package/dist/allocate.d.ts.map +1 -0
- package/dist/allocate.js +314 -0
- package/dist/allocate.js.map +1 -0
- package/dist/bag.d.ts +58 -0
- package/dist/bag.d.ts.map +1 -0
- package/dist/bag.js +122 -0
- package/dist/bag.js.map +1 -0
- package/dist/braintree.d.ts +34 -0
- package/dist/braintree.d.ts.map +1 -0
- package/dist/braintree.js +45 -0
- package/dist/braintree.js.map +1 -0
- package/dist/cash.d.ts +35 -0
- package/dist/cash.d.ts.map +1 -0
- package/dist/cash.js +86 -0
- package/dist/cash.js.map +1 -0
- package/dist/checkout.d.ts +42 -0
- package/dist/checkout.d.ts.map +1 -0
- package/dist/checkout.js +52 -0
- package/dist/checkout.js.map +1 -0
- package/dist/convert.d.ts +51 -0
- package/dist/convert.d.ts.map +1 -0
- package/dist/convert.js +55 -0
- package/dist/convert.js.map +1 -0
- package/dist/currency.d.ts +22 -0
- package/dist/currency.d.ts.map +1 -0
- package/dist/currency.js +38 -0
- package/dist/currency.js.map +1 -0
- package/dist/decimal.d.ts +52 -0
- package/dist/decimal.d.ts.map +1 -0
- package/dist/decimal.js +251 -0
- package/dist/decimal.js.map +1 -0
- package/dist/ecb.d.ts +17 -0
- package/dist/ecb.d.ts.map +1 -0
- package/dist/ecb.js +147 -0
- package/dist/ecb.js.map +1 -0
- package/dist/exact.d.ts +62 -0
- package/dist/exact.d.ts.map +1 -0
- package/dist/exact.js +147 -0
- package/dist/exact.js.map +1 -0
- package/dist/fetch.d.ts +58 -0
- package/dist/fetch.d.ts.map +1 -0
- package/dist/fetch.js +79 -0
- package/dist/fetch.js.map +1 -0
- package/dist/fixed.d.ts +121 -0
- package/dist/fixed.d.ts.map +1 -0
- package/dist/fixed.js +420 -0
- package/dist/fixed.js.map +1 -0
- package/dist/fn.d.ts +27 -0
- package/dist/fn.d.ts.map +1 -0
- package/dist/fn.js +30 -0
- package/dist/fn.js.map +1 -0
- package/dist/format.d.ts +13 -0
- package/dist/format.d.ts.map +1 -0
- package/dist/format.js +90 -0
- package/dist/format.js.map +1 -0
- package/dist/generated/adyen.d.ts +3 -0
- package/dist/generated/adyen.d.ts.map +1 -0
- package/dist/generated/adyen.js +144 -0
- package/dist/generated/adyen.js.map +1 -0
- package/dist/generated/braintree.d.ts +3 -0
- package/dist/generated/braintree.d.ts.map +1 -0
- package/dist/generated/braintree.js +140 -0
- package/dist/generated/braintree.js.map +1 -0
- package/dist/generated/cash.d.ts +12 -0
- package/dist/generated/cash.d.ts.map +1 -0
- package/dist/generated/cash.js +364 -0
- package/dist/generated/cash.js.map +1 -0
- package/dist/generated/checkout.d.ts +3 -0
- package/dist/generated/checkout.d.ts.map +1 -0
- package/dist/generated/checkout.js +151 -0
- package/dist/generated/checkout.js.map +1 -0
- package/dist/generated/iso4217.d.ts +174 -0
- package/dist/generated/iso4217.d.ts.map +1 -0
- package/dist/generated/iso4217.js +175 -0
- package/dist/generated/iso4217.js.map +1 -0
- package/dist/generated/kernel.d.ts +17 -0
- package/dist/generated/kernel.d.ts.map +1 -0
- package/dist/generated/kernel.js +208 -0
- package/dist/generated/kernel.js.map +1 -0
- package/dist/generated/klarna.d.ts +3 -0
- package/dist/generated/klarna.d.ts.map +1 -0
- package/dist/generated/klarna.js +21 -0
- package/dist/generated/klarna.js.map +1 -0
- package/dist/generated/paypal.d.ts +3 -0
- package/dist/generated/paypal.d.ts.map +1 -0
- package/dist/generated/paypal.js +31 -0
- package/dist/generated/paypal.js.map +1 -0
- package/dist/generated/stripe.d.ts +8 -0
- package/dist/generated/stripe.d.ts.map +1 -0
- package/dist/generated/stripe.js +150 -0
- package/dist/generated/stripe.js.map +1 -0
- package/dist/index.d.ts +11 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +11 -0
- package/dist/index.js.map +1 -0
- package/dist/klarna.d.ts +31 -0
- package/dist/klarna.d.ts.map +1 -0
- package/dist/klarna.js +38 -0
- package/dist/klarna.js.map +1 -0
- package/dist/money.d.ts +218 -0
- package/dist/money.d.ts.map +1 -0
- package/dist/money.js +577 -0
- package/dist/money.js.map +1 -0
- package/dist/parse.d.ts +11 -0
- package/dist/parse.d.ts.map +1 -0
- package/dist/parse.js +132 -0
- package/dist/parse.js.map +1 -0
- package/dist/paypal.d.ts +41 -0
- package/dist/paypal.d.ts.map +1 -0
- package/dist/paypal.js +58 -0
- package/dist/paypal.js.map +1 -0
- package/dist/plugins/adyen.d.ts +15 -0
- package/dist/plugins/adyen.d.ts.map +1 -0
- package/dist/plugins/adyen.js +10 -0
- package/dist/plugins/adyen.js.map +1 -0
- package/dist/plugins/all.d.ts +22 -0
- package/dist/plugins/all.d.ts.map +1 -0
- package/dist/plugins/all.js +23 -0
- package/dist/plugins/all.js.map +1 -0
- package/dist/plugins/allocate.d.ts +20 -0
- package/dist/plugins/allocate.d.ts.map +1 -0
- package/dist/plugins/allocate.js +26 -0
- package/dist/plugins/allocate.js.map +1 -0
- package/dist/plugins/braintree.d.ts +12 -0
- package/dist/plugins/braintree.d.ts.map +1 -0
- package/dist/plugins/braintree.js +12 -0
- package/dist/plugins/braintree.js.map +1 -0
- package/dist/plugins/cash.d.ts +19 -0
- package/dist/plugins/cash.d.ts.map +1 -0
- package/dist/plugins/cash.js +16 -0
- package/dist/plugins/cash.js.map +1 -0
- package/dist/plugins/checkout.d.ts +21 -0
- package/dist/plugins/checkout.d.ts.map +1 -0
- package/dist/plugins/checkout.js +16 -0
- package/dist/plugins/checkout.js.map +1 -0
- package/dist/plugins/convert.d.ts +20 -0
- package/dist/plugins/convert.d.ts.map +1 -0
- package/dist/plugins/convert.js +13 -0
- package/dist/plugins/convert.js.map +1 -0
- package/dist/plugins/exact.d.ts +15 -0
- package/dist/plugins/exact.d.ts.map +1 -0
- package/dist/plugins/exact.js +13 -0
- package/dist/plugins/exact.js.map +1 -0
- package/dist/plugins/fixed.d.ts +17 -0
- package/dist/plugins/fixed.d.ts.map +1 -0
- package/dist/plugins/fixed.js +13 -0
- package/dist/plugins/fixed.js.map +1 -0
- package/dist/plugins/format.d.ts +9 -0
- package/dist/plugins/format.d.ts.map +1 -0
- package/dist/plugins/format.js +16 -0
- package/dist/plugins/format.js.map +1 -0
- package/dist/plugins/klarna.d.ts +10 -0
- package/dist/plugins/klarna.d.ts.map +1 -0
- package/dist/plugins/klarna.js +10 -0
- package/dist/plugins/klarna.js.map +1 -0
- package/dist/plugins/paypal.d.ts +14 -0
- package/dist/plugins/paypal.d.ts.map +1 -0
- package/dist/plugins/paypal.js +16 -0
- package/dist/plugins/paypal.js.map +1 -0
- package/dist/plugins/prisma.d.ts +8 -0
- package/dist/plugins/prisma.d.ts.map +1 -0
- package/dist/plugins/prisma.js +13 -0
- package/dist/plugins/prisma.js.map +1 -0
- package/dist/plugins/stripe.d.ts +14 -0
- package/dist/plugins/stripe.d.ts.map +1 -0
- package/dist/plugins/stripe.js +16 -0
- package/dist/plugins/stripe.js.map +1 -0
- package/dist/plugins/tax.d.ts +21 -0
- package/dist/plugins/tax.d.ts.map +1 -0
- package/dist/plugins/tax.js +18 -0
- package/dist/plugins/tax.js.map +1 -0
- package/dist/prisma.d.ts +66 -0
- package/dist/prisma.d.ts.map +1 -0
- package/dist/prisma.js +66 -0
- package/dist/prisma.js.map +1 -0
- package/dist/processor.d.ts +28 -0
- package/dist/processor.d.ts.map +1 -0
- package/dist/processor.js +118 -0
- package/dist/processor.js.map +1 -0
- package/dist/provider.d.ts +89 -0
- package/dist/provider.d.ts.map +1 -0
- package/dist/provider.js +240 -0
- package/dist/provider.js.map +1 -0
- package/dist/rate.d.ts +119 -0
- package/dist/rate.d.ts.map +1 -0
- package/dist/rate.js +271 -0
- package/dist/rate.js.map +1 -0
- package/dist/rounding-error.d.ts +9 -0
- package/dist/rounding-error.d.ts.map +1 -0
- package/dist/rounding-error.js +9 -0
- package/dist/rounding-error.js.map +1 -0
- package/dist/rounding.d.ts +50 -0
- package/dist/rounding.d.ts.map +1 -0
- package/dist/rounding.js +87 -0
- package/dist/rounding.js.map +1 -0
- package/dist/stripe-fx.d.ts +22 -0
- package/dist/stripe-fx.d.ts.map +1 -0
- package/dist/stripe-fx.js +30 -0
- package/dist/stripe-fx.js.map +1 -0
- package/dist/stripe.d.ts +36 -0
- package/dist/stripe.d.ts.map +1 -0
- package/dist/stripe.js +39 -0
- package/dist/stripe.js.map +1 -0
- package/dist/tax.d.ts +29 -0
- package/dist/tax.d.ts.map +1 -0
- package/dist/tax.js +39 -0
- package/dist/tax.js.map +1 -0
- package/package.json +169 -5
- package/src/adyen-fx.ts +154 -0
- package/src/adyen.ts +46 -0
- package/src/allocate.ts +393 -0
- package/src/bag.ts +170 -0
- package/src/braintree.ts +71 -0
- package/src/cash.ts +115 -0
- package/src/checkout.ts +77 -0
- package/src/convert.ts +159 -0
- package/src/currency.ts +61 -0
- package/src/decimal.ts +283 -0
- package/src/ecb.ts +162 -0
- package/src/exact.ts +182 -0
- package/src/fetch.ts +127 -0
- package/src/fixed.ts +558 -0
- package/src/fn.ts +80 -0
- package/src/format.ts +106 -0
- package/src/generated/adyen.ts +144 -0
- package/src/generated/braintree.ts +140 -0
- package/src/generated/cash.ts +375 -0
- package/src/generated/checkout.ts +151 -0
- package/src/generated/iso4217.ts +179 -0
- package/src/generated/kernel.ts +230 -0
- package/src/generated/klarna.ts +21 -0
- package/src/generated/paypal.ts +31 -0
- package/src/generated/stripe.ts +150 -0
- package/src/index.ts +37 -0
- package/src/klarna.ts +54 -0
- package/src/money.ts +781 -0
- package/src/parse.ts +144 -0
- package/src/paypal.ts +93 -0
- package/src/plugins/adyen.ts +25 -0
- package/src/plugins/all.ts +47 -0
- package/src/plugins/allocate.ts +53 -0
- package/src/plugins/braintree.ts +23 -0
- package/src/plugins/cash.ts +33 -0
- package/src/plugins/checkout.ts +32 -0
- package/src/plugins/convert.ts +50 -0
- package/src/plugins/exact.ts +23 -0
- package/src/plugins/fixed.ts +28 -0
- package/src/plugins/format.ts +28 -0
- package/src/plugins/klarna.ts +21 -0
- package/src/plugins/paypal.ts +29 -0
- package/src/plugins/prisma.ts +24 -0
- package/src/plugins/stripe.ts +29 -0
- package/src/plugins/tax.ts +41 -0
- package/src/prisma.ts +118 -0
- package/src/processor.ts +181 -0
- package/src/provider.ts +324 -0
- package/src/rate.ts +377 -0
- package/src/rounding-error.ts +8 -0
- package/src/rounding.ts +122 -0
- package/src/stripe-fx.ts +49 -0
- package/src/stripe.ts +69 -0
- package/src/tax.ts +71 -0
package/src/cash.ts
ADDED
|
@@ -0,0 +1,115 @@
|
|
|
1
|
+
import { CASH_RULES, type CashRule } from './generated/cash.js';
|
|
2
|
+
import { CurrencyMismatchError, make, scaleUp, toScale, type Money } from './money.js';
|
|
3
|
+
import { divideAndRound, divideAndRoundBigint, type RoundingMode } from './rounding.js';
|
|
4
|
+
import { currencyExponent } from './currency.js';
|
|
5
|
+
|
|
6
|
+
/**
|
|
7
|
+
* Rounds to a multiple of `increment` (same currency): roundToIncrement(CHF 10.03, CHF 0.05) = CHF
|
|
8
|
+
* 10.05. Default rounding 'halfExpand' (nearest, ties away from zero), which is what the statutory
|
|
9
|
+
* cash-rounding rules (SE, NO, DK, HU, CZ, FI, BE ...) prescribe.
|
|
10
|
+
*/
|
|
11
|
+
export function roundToIncrement<C extends string>(
|
|
12
|
+
money: Money<C>,
|
|
13
|
+
increment: Money<NoInfer<C>>,
|
|
14
|
+
rounding: RoundingMode = 'halfExpand',
|
|
15
|
+
): Money<C> {
|
|
16
|
+
if (money.currency !== increment.currency) {
|
|
17
|
+
throw new CurrencyMismatchError(money.currency, increment.currency);
|
|
18
|
+
}
|
|
19
|
+
if (!(increment.minor > 0)) {
|
|
20
|
+
throw new RangeError('increment must be positive');
|
|
21
|
+
}
|
|
22
|
+
const scale = Math.max(money.scale, increment.scale);
|
|
23
|
+
const minor = scaleUp(money.minor, scale - money.scale);
|
|
24
|
+
const step = scaleUp(increment.minor, scale - increment.scale);
|
|
25
|
+
if (typeof minor === 'number' && typeof step === 'number') {
|
|
26
|
+
const steps = divideAndRound(minor, step, rounding);
|
|
27
|
+
const rounded = steps * step;
|
|
28
|
+
if (Number.isSafeInteger(rounded)) {
|
|
29
|
+
return toScale(
|
|
30
|
+
make(money.currency, rounded, scale),
|
|
31
|
+
money.scale > scale ? money.scale : scale,
|
|
32
|
+
);
|
|
33
|
+
}
|
|
34
|
+
}
|
|
35
|
+
return make(
|
|
36
|
+
money.currency,
|
|
37
|
+
divideAndRoundBigint(BigInt(minor), BigInt(step), rounding) * BigInt(step),
|
|
38
|
+
scale,
|
|
39
|
+
);
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
/**
|
|
43
|
+
* The cash-rounding rule for a currency, optionally narrowed by country (ISO 3166 alpha-2).
|
|
44
|
+
* EUR has no euro-wide rule: pass the country (BE, NL, FI, IE, IT, SK, EE, LT).
|
|
45
|
+
*/
|
|
46
|
+
export function cashRule(currency: string, country?: string): CashRule | undefined {
|
|
47
|
+
const rules = cashRulesFor(currency);
|
|
48
|
+
if (rules === undefined) {
|
|
49
|
+
return undefined;
|
|
50
|
+
}
|
|
51
|
+
if (country !== undefined) {
|
|
52
|
+
for (let i = 0; i < rules.length; i++) {
|
|
53
|
+
if (rules[i]!.countries.includes(country)) {
|
|
54
|
+
return rules[i];
|
|
55
|
+
}
|
|
56
|
+
}
|
|
57
|
+
return undefined;
|
|
58
|
+
}
|
|
59
|
+
// EUR has no euro-wide rule, so it needs a country
|
|
60
|
+
if (currency === 'EUR') {
|
|
61
|
+
return undefined;
|
|
62
|
+
}
|
|
63
|
+
return rules[0];
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
// CASH_RULES grouped by currency, in table order. Built on first use, not at import, so the module
|
|
67
|
+
// stays free of side effects; cashRound calls cashRule on every amount, and a scan of the whole table
|
|
68
|
+
// was most of its cost.
|
|
69
|
+
let rulesByCurrency: Map<string, CashRule[]> | undefined;
|
|
70
|
+
|
|
71
|
+
function cashRulesFor(currency: string): readonly CashRule[] | undefined {
|
|
72
|
+
if (rulesByCurrency === undefined) {
|
|
73
|
+
rulesByCurrency = new Map();
|
|
74
|
+
for (let i = 0; i < CASH_RULES.length; i++) {
|
|
75
|
+
const rule = CASH_RULES[i]!;
|
|
76
|
+
const forCurrency = rulesByCurrency.get(rule.currency);
|
|
77
|
+
if (forCurrency === undefined) {
|
|
78
|
+
rulesByCurrency.set(rule.currency, [rule]);
|
|
79
|
+
} else {
|
|
80
|
+
forCurrency.push(rule);
|
|
81
|
+
}
|
|
82
|
+
}
|
|
83
|
+
}
|
|
84
|
+
return rulesByCurrency.get(currency);
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
/**
|
|
88
|
+
* Options for `cashRound`: the country (needed for EUR), the rounding mode, and whether to use
|
|
89
|
+
* unverified rules.
|
|
90
|
+
*/
|
|
91
|
+
export interface CashRoundOptions {
|
|
92
|
+
readonly country?: string;
|
|
93
|
+
readonly rounding?: RoundingMode;
|
|
94
|
+
/**
|
|
95
|
+
* Apply rules that are only backed by secondary sources (default true; see
|
|
96
|
+
* data/cash-rounding.json).
|
|
97
|
+
*/
|
|
98
|
+
readonly includeUnverified?: boolean;
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
/**
|
|
102
|
+
* Rounds a cash total to the smallest legal/practical cash step (CHF 0.05, SEK 1, DKK 0.50, CAD
|
|
103
|
+
* 0.05, HUF 5, EUR 0.05 in BE/NL/FI/IE/...). Card and other electronic payments are NOT rounded:
|
|
104
|
+
* only call this for cash tenders. Returns m unchanged when no rule applies.
|
|
105
|
+
*/
|
|
106
|
+
export function cashRound<C extends string>(money: Money<C>, options?: CashRoundOptions): Money<C> {
|
|
107
|
+
const rule = cashRule(money.currency, options?.country);
|
|
108
|
+
if (!rule || (options?.includeUnverified === false && !rule.verified)) {
|
|
109
|
+
return money;
|
|
110
|
+
}
|
|
111
|
+
const inc = make(money.currency, rule.increment, currencyExponent(money.currency));
|
|
112
|
+
return roundToIncrement(money, inc, options?.rounding ?? 'halfExpand');
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
export { CASH_RULES, type CashRule };
|
package/src/checkout.ts
ADDED
|
@@ -0,0 +1,77 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Checkout.com's amount view (https://www.checkout.com/docs/payments/accept-payments/format-the-amount-value,
|
|
3
|
+
* encoded in data/checkout.json). `amount` is an integer:
|
|
4
|
+
* - the full amount: BIF DJF GNF ISK JPY KMF KRW PYG RWF UGX VUV VND XAF XOF XPF
|
|
5
|
+
* - divided by 1000, last digit 0: BHD IQD JOD KWD LYD OMR TND
|
|
6
|
+
* - divided by 100 for every other currency. CLP is here too (ISO says 0 decimals), and for payment
|
|
7
|
+
* requests its last two digits must be 00 (5000 CLP -> 500000). Standalone authentication is
|
|
8
|
+
* exempt.
|
|
9
|
+
*/
|
|
10
|
+
import { CHECKOUT_RULES } from './generated/checkout.js';
|
|
11
|
+
import { type CurrencyInput, type Money } from './money.js';
|
|
12
|
+
import { fromProcessorAmount, toProcessorAmount } from './processor.js';
|
|
13
|
+
import type { RoundingMode } from './rounding.js';
|
|
14
|
+
|
|
15
|
+
export { CHECKOUT_RULES };
|
|
16
|
+
|
|
17
|
+
/** Checkout.com's [exponent, payment multiple, Standalone API multiple] for a currency. */
|
|
18
|
+
function rulesFor(currency: string) {
|
|
19
|
+
const rules = CHECKOUT_RULES[currency.toUpperCase()];
|
|
20
|
+
if (!rules) {
|
|
21
|
+
throw new RangeError(`${currency} is not a Checkout.com currency`);
|
|
22
|
+
}
|
|
23
|
+
return rules;
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
/** Whether Checkout.com lists the currency (case-insensitive). */
|
|
27
|
+
export function isCheckoutCurrency(currency: string): boolean {
|
|
28
|
+
return CHECKOUT_RULES[currency.toUpperCase()] !== undefined;
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
/** The exponent Checkout.com's API uses for a currency (CLP 2, JPY 0, BHD 3). */
|
|
32
|
+
export function checkoutExponent(currency: string): number {
|
|
33
|
+
return rulesFor(currency)[0];
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
/** Options for the Checkout.com amount: how to round when Checkout.com needs a coarser amount. */
|
|
37
|
+
export interface CheckoutAmountOptions {
|
|
38
|
+
/** How to round when Checkout.com needs a coarser amount (default 'unnecessary': throw). */
|
|
39
|
+
readonly rounding?: RoundingMode;
|
|
40
|
+
/**
|
|
41
|
+
* An authentication request to the Standalone API, where CLP's "last two digits 00" rule does not
|
|
42
|
+
* apply.
|
|
43
|
+
*/
|
|
44
|
+
readonly standalone?: boolean;
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
/**
|
|
48
|
+
* The integer `amount` to send, e.g. toCheckoutAmount(money('5000', 'CLP')) === 500000.
|
|
49
|
+
* Throws a RangeError for negative amounts (refunds are sent as positive amounts).
|
|
50
|
+
* SLL and XDR are on Checkout.com's list but not in ISO 4217's active list: call
|
|
51
|
+
* `defineCurrency('SLL', 2)` or `defineCurrency('XDR', 2)` before using them.
|
|
52
|
+
*/
|
|
53
|
+
export function toCheckoutAmount(money: Money, options?: CheckoutAmountOptions): number {
|
|
54
|
+
const [exponent, paymentMultiple, standaloneMultiple] = rulesFor(money.currency);
|
|
55
|
+
const multiple = options?.standalone ? standaloneMultiple : paymentMultiple;
|
|
56
|
+
const rounding = options?.rounding ?? 'unnecessary';
|
|
57
|
+
|
|
58
|
+
// "Be greater than zero", except 0 for a card verification (API reference); refunds are positive.
|
|
59
|
+
return toProcessorAmount('Checkout.com', money, exponent, multiple, rounding, 'nonNegative');
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
/** `{ amount, currency }` for a payment request. */
|
|
63
|
+
export function toCheckout(
|
|
64
|
+
money: Money,
|
|
65
|
+
options?: CheckoutAmountOptions,
|
|
66
|
+
): { amount: number; currency: string } {
|
|
67
|
+
return { amount: toCheckoutAmount(money, options), currency: money.currency.toUpperCase() };
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
/** Reads a Checkout.com amount: fromCheckout(500000, 'CLP') is 5000 CLP. */
|
|
71
|
+
export function fromCheckout<C extends CurrencyInput>(
|
|
72
|
+
amount: number | bigint,
|
|
73
|
+
currency: C,
|
|
74
|
+
): Money<Uppercase<C>> {
|
|
75
|
+
const code = currency.toUpperCase() as Uppercase<C>;
|
|
76
|
+
return fromProcessorAmount('Checkout.com', amount, code, checkoutExponent(code));
|
|
77
|
+
}
|
package/src/convert.ts
ADDED
|
@@ -0,0 +1,159 @@
|
|
|
1
|
+
// `ducat/convert` free functions: exact exchange rates and conversion that rounds once.
|
|
2
|
+
import { currencyExponent } from './currency.js';
|
|
3
|
+
import { exact, type Rounded } from './exact.js';
|
|
4
|
+
import { ratio, type Factor } from './decimal.js';
|
|
5
|
+
import { make, type CurrencyInput, type Money } from './money.js';
|
|
6
|
+
import { rateOf, type RateProvider } from './provider.js';
|
|
7
|
+
import { isRate, multiplyByRatioAtScale, type ConvertOptions, type Rate } from './rate.js';
|
|
8
|
+
import { DEFAULT_ROUNDING, type RoundingMode } from './rounding.js';
|
|
9
|
+
|
|
10
|
+
export {
|
|
11
|
+
exchangeRate,
|
|
12
|
+
impliedRate,
|
|
13
|
+
isRate,
|
|
14
|
+
multiplyByRatioAtScale,
|
|
15
|
+
Rate,
|
|
16
|
+
RateExpiredError,
|
|
17
|
+
rateFromJSON,
|
|
18
|
+
type ConvertOptions,
|
|
19
|
+
type RateInfo,
|
|
20
|
+
type RateJSON,
|
|
21
|
+
type RateType,
|
|
22
|
+
} from './rate.js';
|
|
23
|
+
export {
|
|
24
|
+
bag,
|
|
25
|
+
comparator,
|
|
26
|
+
MoneyBag,
|
|
27
|
+
sortByValue,
|
|
28
|
+
sumByCurrency,
|
|
29
|
+
type ComparatorOptions,
|
|
30
|
+
type TotalOptions,
|
|
31
|
+
} from './bag.js';
|
|
32
|
+
export {
|
|
33
|
+
chain,
|
|
34
|
+
identity,
|
|
35
|
+
rateOf,
|
|
36
|
+
rateTable,
|
|
37
|
+
RateUnavailableError,
|
|
38
|
+
reversed,
|
|
39
|
+
snapshots,
|
|
40
|
+
snapshotsFrom,
|
|
41
|
+
via,
|
|
42
|
+
type RateProvider,
|
|
43
|
+
type RateQuery,
|
|
44
|
+
type RateTable,
|
|
45
|
+
type RateTableSpec,
|
|
46
|
+
type SnapshotOptions,
|
|
47
|
+
type Snapshots,
|
|
48
|
+
} from './provider.js';
|
|
49
|
+
|
|
50
|
+
/** Options for converting through a provider. */
|
|
51
|
+
export interface ProviderConvertOptions extends ConvertOptions {
|
|
52
|
+
/** The time the rate is wanted for (an ISO-8601 date or instant, or a Date). */
|
|
53
|
+
readonly asOf?: string | Date;
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
function isProvider(value: unknown): value is RateProvider {
|
|
57
|
+
return typeof (value as RateProvider | undefined)?.rate === 'function';
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
/**
|
|
61
|
+
* Converts `money` at a Rate, rounding once to the target currency's exponent (or `options.scale`).
|
|
62
|
+
* The rate's pair is checked, at compile time for literal currencies and at run time otherwise.
|
|
63
|
+
*
|
|
64
|
+
* convert(money('100', 'EUR'), eurUsd, 'halfEven') // 111.65 USD
|
|
65
|
+
* convert(money('100', 'USD'), eurUsd.inverse().andThen(eurJpy)) // composed exactly, rounded once
|
|
66
|
+
*/
|
|
67
|
+
export function convert<From extends string, To extends string>(
|
|
68
|
+
money: Money<From>,
|
|
69
|
+
rate: Rate<NoInfer<From>, To>,
|
|
70
|
+
rounding?: RoundingMode,
|
|
71
|
+
options?: ConvertOptions,
|
|
72
|
+
): Money<To>;
|
|
73
|
+
/**
|
|
74
|
+
* Converts at a bare rate: units of `to` per unit of money's currency, as a decimal string so that
|
|
75
|
+
* no float is involved ('1.0832', every digit kept). Rounds once.
|
|
76
|
+
*
|
|
77
|
+
* convert(money('100', 'EUR'), 'JPY', '162.457', 'halfEven') // 16246 JPY
|
|
78
|
+
*/
|
|
79
|
+
export function convert<To extends CurrencyInput>(
|
|
80
|
+
money: Money,
|
|
81
|
+
to: To,
|
|
82
|
+
rate: Factor,
|
|
83
|
+
rounding?: RoundingMode,
|
|
84
|
+
options?: ConvertOptions,
|
|
85
|
+
): Money<To>;
|
|
86
|
+
/**
|
|
87
|
+
* Converts through a provider: looks up money's currency → `to` (as of `options.asOf`) and rounds
|
|
88
|
+
* once. Throws RateUnavailableError when the provider has no rate.
|
|
89
|
+
*
|
|
90
|
+
* convert(money('100', 'USD'), 'JPY', via('EUR', ecb), 'halfEven')
|
|
91
|
+
*/
|
|
92
|
+
export function convert<To extends CurrencyInput>(
|
|
93
|
+
money: Money,
|
|
94
|
+
to: To,
|
|
95
|
+
provider: RateProvider,
|
|
96
|
+
rounding?: RoundingMode,
|
|
97
|
+
options?: ProviderConvertOptions,
|
|
98
|
+
): Money<To>;
|
|
99
|
+
export function convert(
|
|
100
|
+
money: Money,
|
|
101
|
+
rateOrTarget: Rate | string,
|
|
102
|
+
roundingOrRate?: RoundingMode | Factor | RateProvider,
|
|
103
|
+
optionsOrRounding?: ConvertOptions | RoundingMode,
|
|
104
|
+
maybeOptions?: ProviderConvertOptions,
|
|
105
|
+
): Money {
|
|
106
|
+
if (isRate(rateOrTarget)) {
|
|
107
|
+
const rounding = roundingOrRate as RoundingMode | undefined;
|
|
108
|
+
return rateOrTarget.convert(money, rounding, optionsOrRounding as ConvertOptions | undefined);
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
const to = rateOrTarget;
|
|
112
|
+
if (isProvider(roundingOrRate)) {
|
|
113
|
+
let query: { asOf: string | Date } | undefined;
|
|
114
|
+
if (maybeOptions?.asOf !== undefined) {
|
|
115
|
+
query = { asOf: maybeOptions.asOf };
|
|
116
|
+
}
|
|
117
|
+
const rate = rateOf(roundingOrRate, money.currency, to, query);
|
|
118
|
+
return rate.convert(money, optionsOrRounding as RoundingMode | undefined, maybeOptions);
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
// The bare-rate form converts directly, without building a Rate, to keep it allocation-light.
|
|
122
|
+
let rate = ratio(roundingOrRate as Factor);
|
|
123
|
+
if (typeof roundingOrRate === 'object') {
|
|
124
|
+
// A hand-made Ratio object is passed through by ratio(); rebuild it so it is reduced and its
|
|
125
|
+
// number fields match its bigints. Strings and numbers are already normalised (and cached).
|
|
126
|
+
rate = ratio(rate.num, rate.den);
|
|
127
|
+
}
|
|
128
|
+
if (rate.num <= 0n) {
|
|
129
|
+
throw new RangeError('Exchange rate must be positive');
|
|
130
|
+
}
|
|
131
|
+
const rounding = (optionsOrRounding as RoundingMode | undefined) ?? DEFAULT_ROUNDING;
|
|
132
|
+
const scale = maybeOptions?.scale ?? currencyExponent(to);
|
|
133
|
+
const minor = multiplyByRatioAtScale(money.minor, rate, scale - money.scale, rounding);
|
|
134
|
+
return make(to, minor, scale);
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
/**
|
|
138
|
+
* A conversion's rounded value, what rounding left out, and the rate used (for the audit trail).
|
|
139
|
+
*/
|
|
140
|
+
export interface DetailedConversion<From extends string, To extends string> extends Rounded<To> {
|
|
141
|
+
readonly rate: Rate<From, To>;
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
/**
|
|
145
|
+
* Converts at `rate` like convert(), and also reports the residual: `value + residual` is exactly
|
|
146
|
+
* money × rate, so a ledger can book the rounding difference.
|
|
147
|
+
*
|
|
148
|
+
* const { value, residual } = convertDetailed(money('0.07', 'EUR'), eurUsd, 'halfEven');
|
|
149
|
+
* // value 0.08 USD, residual -0.001845 USD (as an exact ExactMoney)
|
|
150
|
+
*/
|
|
151
|
+
export function convertDetailed<From extends string, To extends string>(
|
|
152
|
+
money: Money<From>,
|
|
153
|
+
rate: Rate<NoInfer<From>, To>,
|
|
154
|
+
rounding: RoundingMode = DEFAULT_ROUNDING,
|
|
155
|
+
options?: ConvertOptions,
|
|
156
|
+
): DetailedConversion<From, To> {
|
|
157
|
+
const rounded = exact(money).convert(rate).roundWithResidual(rounding, options?.scale);
|
|
158
|
+
return { value: rounded.value, residual: rounded.residual, rate };
|
|
159
|
+
}
|
package/src/currency.ts
ADDED
|
@@ -0,0 +1,61 @@
|
|
|
1
|
+
import { ISO_EXPONENTS, type IsoCurrencyCode } from './generated/iso4217.js';
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* Augment this interface to add non-ISO currencies to the `CurrencyCode` type:
|
|
5
|
+
*
|
|
6
|
+
* declare module '@ducatjs/money' { interface CustomCurrencies { BTC: true; USDC: true } }
|
|
7
|
+
* defineCurrency('BTC', 8);
|
|
8
|
+
*/
|
|
9
|
+
// eslint-disable-next-line @typescript-eslint/no-empty-interface
|
|
10
|
+
export interface CustomCurrencies {}
|
|
11
|
+
|
|
12
|
+
/** A known currency code: ISO 4217, or one added to `CustomCurrencies`. */
|
|
13
|
+
export type CurrencyCode = IsoCurrencyCode | (keyof CustomCurrencies & string);
|
|
14
|
+
|
|
15
|
+
const custom = new Map<string, number>();
|
|
16
|
+
const iso = ISO_EXPONENTS as Readonly<Record<string, number>>;
|
|
17
|
+
|
|
18
|
+
/**
|
|
19
|
+
* Registers a currency that is not in ISO 4217 (crypto, loyalty points, withdrawn codes you still
|
|
20
|
+
* hold balances in). ISO codes cannot be redefined: use an explicit `scale` for extra precision.
|
|
21
|
+
*/
|
|
22
|
+
export function defineCurrency(code: string, exponent: number): void {
|
|
23
|
+
if (!Number.isInteger(exponent) || exponent < 0 || exponent > 30) {
|
|
24
|
+
throw new RangeError(`Invalid exponent ${exponent}`);
|
|
25
|
+
}
|
|
26
|
+
if (typeof iso[code] === 'number') {
|
|
27
|
+
throw new TypeError(`${code} is an ISO 4217 currency and cannot be redefined`);
|
|
28
|
+
}
|
|
29
|
+
const prev = custom.get(code);
|
|
30
|
+
if (prev !== undefined && prev !== exponent) {
|
|
31
|
+
throw new TypeError(`${code} is already defined with exponent ${prev}`);
|
|
32
|
+
}
|
|
33
|
+
custom.set(code, exponent);
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
/** The minor-unit exponent of a currency (EUR 2, JPY 0, KWD 3). Throws for unknown codes. */
|
|
37
|
+
export function currencyExponent(code: string): number {
|
|
38
|
+
const isoExponent = iso[code];
|
|
39
|
+
if (typeof isoExponent === 'number') {
|
|
40
|
+
return isoExponent;
|
|
41
|
+
}
|
|
42
|
+
const customExponent = custom.get(code);
|
|
43
|
+
if (customExponent !== undefined) {
|
|
44
|
+
return customExponent;
|
|
45
|
+
}
|
|
46
|
+
throw new RangeError(
|
|
47
|
+
`Unknown currency "${code}" (not ISO 4217 and not registered with defineCurrency)`,
|
|
48
|
+
);
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
/** Whether the code is an ISO 4217 currency or one registered with `defineCurrency`. */
|
|
52
|
+
export function isCurrency(code: string): code is CurrencyCode {
|
|
53
|
+
return typeof iso[code] === 'number' || custom.has(code);
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
export {
|
|
57
|
+
ISO_EXPONENTS,
|
|
58
|
+
ISO_4217_PUBLISHED,
|
|
59
|
+
ISO_NON_MONETARY,
|
|
60
|
+
type IsoCurrencyCode,
|
|
61
|
+
} from './generated/iso4217.js';
|
package/src/decimal.ts
ADDED
|
@@ -0,0 +1,283 @@
|
|
|
1
|
+
// Exact decimal-string handling. No floating point is used on amounts: numbers given as factors are
|
|
2
|
+
// converted through their shortest round-trip decimal representation (String(x)), never multiplied.
|
|
3
|
+
|
|
4
|
+
/** The largest minor-unit count held as a number (2^53 - 1); larger values are bigints. */
|
|
5
|
+
const MAX_SAFE_MINOR = Number.MAX_SAFE_INTEGER;
|
|
6
|
+
const MAXN = BigInt(MAX_SAFE_MINOR);
|
|
7
|
+
|
|
8
|
+
/**
|
|
9
|
+
* An exact rational factor num/den (den > 0). `n`/`d` hold the same values as numbers when both are
|
|
10
|
+
* safe.
|
|
11
|
+
*/
|
|
12
|
+
export interface Ratio {
|
|
13
|
+
readonly num: bigint;
|
|
14
|
+
readonly den: bigint;
|
|
15
|
+
/** num as a number, or NaN when it is not a safe integer */
|
|
16
|
+
readonly n: number;
|
|
17
|
+
/** den as a number, or NaN when it is not a safe integer */
|
|
18
|
+
readonly d: number;
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
/** Anything accepted where a multiplier, rate or percentage is expected. */
|
|
22
|
+
export type Factor = number | bigint | string | Ratio;
|
|
23
|
+
|
|
24
|
+
const POW10N: bigint[] = [];
|
|
25
|
+
/** 10^exponent as a bigint, cached. */
|
|
26
|
+
export function pow10n(exponent: number): bigint {
|
|
27
|
+
return (POW10N[exponent] ??= 10n ** BigInt(exponent));
|
|
28
|
+
}
|
|
29
|
+
/** 10^e as a number for 0 <= e <= 15 (all exact and safe). */
|
|
30
|
+
export const POW10 = [
|
|
31
|
+
1, 10, 100, 1e3, 1e4, 1e5, 1e6, 1e7, 1e8, 1e9, 1e10, 1e11, 1e12, 1e13, 1e14, 1e15,
|
|
32
|
+
] as const;
|
|
33
|
+
|
|
34
|
+
/**
|
|
35
|
+
* A bigint as a number when it is a safe integer, else unchanged: the representation Money keeps.
|
|
36
|
+
*/
|
|
37
|
+
export const normalizeMinor = (value: bigint): number | bigint =>
|
|
38
|
+
value <= MAXN && value >= -MAXN ? Number(value) : value;
|
|
39
|
+
|
|
40
|
+
/**
|
|
41
|
+
* Parses a plain decimal string ("-12.345", "+7", "0.50") into digits/10^scale. Returns the integer
|
|
42
|
+
* of all digits (number when safe, else bigint) and the count of fraction digits. Hand-rolled (no
|
|
43
|
+
* regex, no BigInt for short inputs): this is the hot path of `money("12.34", ...)`.
|
|
44
|
+
*/
|
|
45
|
+
export function parsePlainDecimal(
|
|
46
|
+
input: string,
|
|
47
|
+
): { digits: number | bigint; scale: number } | null {
|
|
48
|
+
const len = input.length;
|
|
49
|
+
let i = 0;
|
|
50
|
+
let neg = false;
|
|
51
|
+
let code = input.charCodeAt(0);
|
|
52
|
+
if (code === 45 /* - */ || code === 43 /* + */) {
|
|
53
|
+
neg = code === 45;
|
|
54
|
+
i = 1;
|
|
55
|
+
}
|
|
56
|
+
let acc = 0;
|
|
57
|
+
let digitsSeen = 0;
|
|
58
|
+
let scale = -1;
|
|
59
|
+
let big = false;
|
|
60
|
+
const start = i;
|
|
61
|
+
for (; i < len; i++) {
|
|
62
|
+
code = input.charCodeAt(i);
|
|
63
|
+
if (code >= 48 && code <= 57) {
|
|
64
|
+
digitsSeen++;
|
|
65
|
+
if (scale >= 0) {
|
|
66
|
+
scale++;
|
|
67
|
+
}
|
|
68
|
+
if (!big) {
|
|
69
|
+
// 15 digits always fit exactly in a double; beyond that use BigInt
|
|
70
|
+
if (digitsSeen > 15) {
|
|
71
|
+
big = true;
|
|
72
|
+
} else {
|
|
73
|
+
acc = acc * 10 + (code - 48);
|
|
74
|
+
}
|
|
75
|
+
}
|
|
76
|
+
} else if (code === 46 /* . */ && scale < 0 && digitsSeen > 0) {
|
|
77
|
+
scale = 0;
|
|
78
|
+
} else {
|
|
79
|
+
return null;
|
|
80
|
+
}
|
|
81
|
+
}
|
|
82
|
+
// "", "-" and "12." are not decimals
|
|
83
|
+
if (digitsSeen === 0 || scale === 0) {
|
|
84
|
+
return null;
|
|
85
|
+
}
|
|
86
|
+
// parseDecimal reports fractions longer than MAX_DECIMAL_SCALE
|
|
87
|
+
if (scale > MAX_DECIMAL_SCALE) {
|
|
88
|
+
return null;
|
|
89
|
+
}
|
|
90
|
+
if (scale < 0) {
|
|
91
|
+
scale = 0;
|
|
92
|
+
}
|
|
93
|
+
if (big) {
|
|
94
|
+
const raw = input.slice(start).replace('.', '');
|
|
95
|
+
const value = BigInt(raw);
|
|
96
|
+
return { digits: normalizeMinor(neg ? -value : value), scale };
|
|
97
|
+
}
|
|
98
|
+
return { digits: neg ? 0 - acc : acc, scale };
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
const EXP_RE = /^([+-]?)(\d+)(?:\.(\d+))?(?:[eE]([+-]?\d+))?$/;
|
|
102
|
+
|
|
103
|
+
/**
|
|
104
|
+
* The largest exponent and number of fraction digits a decimal string may have. Far beyond any real
|
|
105
|
+
* amount or rate, and it keeps input such as "1e999999999" from building enormous powers of ten.
|
|
106
|
+
*/
|
|
107
|
+
export const MAX_DECIMAL_SCALE = 1000;
|
|
108
|
+
|
|
109
|
+
/** Parses a decimal string, allowing exponent notation ("1e-7", as produced by String(1e-7)). */
|
|
110
|
+
export function parseDecimal(input: string): { digits: bigint; scale: number } {
|
|
111
|
+
const match = EXP_RE.exec(input.trim());
|
|
112
|
+
if (!match) {
|
|
113
|
+
throw new SyntaxError(`Invalid decimal string "${input}"`);
|
|
114
|
+
}
|
|
115
|
+
const [, sign, int, frac = '', exp = '0'] = match;
|
|
116
|
+
const exponent = Number(exp);
|
|
117
|
+
let scale = frac.length - exponent;
|
|
118
|
+
if (!(Math.abs(exponent) <= MAX_DECIMAL_SCALE) || scale > MAX_DECIMAL_SCALE) {
|
|
119
|
+
// The input itself is not quoted: it may be huge.
|
|
120
|
+
throw new RangeError(`Decimal string exponent or fraction digits beyond ${MAX_DECIMAL_SCALE}`);
|
|
121
|
+
}
|
|
122
|
+
let digits = BigInt(int! + frac);
|
|
123
|
+
if (scale < 0) {
|
|
124
|
+
digits *= pow10n(-scale);
|
|
125
|
+
scale = 0;
|
|
126
|
+
}
|
|
127
|
+
return { digits: sign === '-' ? -digits : digits, scale };
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
function gcd(left: bigint, right: bigint): bigint {
|
|
131
|
+
if (left < 0n) {
|
|
132
|
+
left = -left;
|
|
133
|
+
}
|
|
134
|
+
// a temporary, not a destructuring swap: `[a, b] = [b, a % b]` builds an array per step until the
|
|
135
|
+
// optimiser removes it, and this loop runs for every ratio that is built
|
|
136
|
+
while (right) {
|
|
137
|
+
const remainder = left % right;
|
|
138
|
+
left = right;
|
|
139
|
+
right = remainder;
|
|
140
|
+
}
|
|
141
|
+
return left;
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
/** The value as a number when it is a safe integer, otherwise NaN (a Ratio's `n` and `d`). */
|
|
145
|
+
function safeNumberOrNaN(value: bigint): number {
|
|
146
|
+
return value <= MAXN && value >= -MAXN ? Number(value) : NaN;
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
function makeRatio(num: bigint, den: bigint): Ratio {
|
|
150
|
+
if (den === 0n) {
|
|
151
|
+
throw new RangeError('Division by zero');
|
|
152
|
+
}
|
|
153
|
+
if (den < 0n) {
|
|
154
|
+
num = -num;
|
|
155
|
+
den = -den;
|
|
156
|
+
}
|
|
157
|
+
// an integer (den 1) is already in lowest terms
|
|
158
|
+
if (den !== 1n) {
|
|
159
|
+
const divisor = gcd(num, den);
|
|
160
|
+
if (divisor > 1n) {
|
|
161
|
+
num /= divisor;
|
|
162
|
+
den /= divisor;
|
|
163
|
+
}
|
|
164
|
+
}
|
|
165
|
+
return { num, den, n: safeNumberOrNaN(num), d: safeNumberOrNaN(den) };
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
const cache = new Map<string, Ratio>();
|
|
169
|
+
const INT_RATIOS: Ratio[] = [];
|
|
170
|
+
|
|
171
|
+
/**
|
|
172
|
+
* Builds an exact ratio. `ratio('1.075')`, `ratio(3, 4)`, `ratio(10n)`, `ratio('1/3')`.
|
|
173
|
+
* Numbers are taken at their shortest decimal representation: `ratio(0.1)` is exactly 1/10.
|
|
174
|
+
* Pre-build ratios you use in hot loops; strings are also cached (up to 1024 entries).
|
|
175
|
+
*/
|
|
176
|
+
export function ratio(value: Factor, den?: Factor): Ratio {
|
|
177
|
+
if (den !== undefined) {
|
|
178
|
+
// two bigints (divide, percentages, tax): one reduction instead of three
|
|
179
|
+
if (typeof value === 'bigint' && typeof den === 'bigint') {
|
|
180
|
+
return makeRatio(value, den);
|
|
181
|
+
}
|
|
182
|
+
const numeratorRatio = ratio(value);
|
|
183
|
+
const denominatorRatio = ratio(den);
|
|
184
|
+
return makeRatio(
|
|
185
|
+
numeratorRatio.num * denominatorRatio.den,
|
|
186
|
+
numeratorRatio.den * denominatorRatio.num,
|
|
187
|
+
);
|
|
188
|
+
}
|
|
189
|
+
if (typeof value === 'object') {
|
|
190
|
+
return value;
|
|
191
|
+
}
|
|
192
|
+
if (typeof value === 'number') {
|
|
193
|
+
if (Number.isSafeInteger(value)) {
|
|
194
|
+
if (value >= 0 && value < 128) {
|
|
195
|
+
return (INT_RATIOS[value] ??= makeRatio(BigInt(value), 1n));
|
|
196
|
+
}
|
|
197
|
+
return makeRatio(BigInt(value), 1n);
|
|
198
|
+
}
|
|
199
|
+
if (!Number.isFinite(value)) {
|
|
200
|
+
throw new RangeError(`Invalid factor ${value}`);
|
|
201
|
+
}
|
|
202
|
+
value = String(value);
|
|
203
|
+
}
|
|
204
|
+
if (typeof value === 'bigint') {
|
|
205
|
+
return makeRatio(value, 1n);
|
|
206
|
+
}
|
|
207
|
+
let cached = cache.get(value);
|
|
208
|
+
if (cached === undefined) {
|
|
209
|
+
const slash = value.indexOf('/');
|
|
210
|
+
if (slash > 0) {
|
|
211
|
+
cached = ratio(value.slice(0, slash).trim(), value.slice(slash + 1).trim());
|
|
212
|
+
} else {
|
|
213
|
+
const { digits, scale } = parseDecimal(value);
|
|
214
|
+
cached = makeRatio(digits, pow10n(scale));
|
|
215
|
+
}
|
|
216
|
+
if (cache.size >= 1024) {
|
|
217
|
+
cache.clear();
|
|
218
|
+
}
|
|
219
|
+
cache.set(value, cached);
|
|
220
|
+
}
|
|
221
|
+
return cached;
|
|
222
|
+
}
|
|
223
|
+
|
|
224
|
+
/** num/den -> exact decimal string if the expansion terminates, else null. */
|
|
225
|
+
export function ratioToDecimal(value: Ratio): string | null {
|
|
226
|
+
let remainingDenominator = value.den;
|
|
227
|
+
let twos = 0;
|
|
228
|
+
let fives = 0;
|
|
229
|
+
while (remainingDenominator % 2n === 0n) {
|
|
230
|
+
remainingDenominator /= 2n;
|
|
231
|
+
twos++;
|
|
232
|
+
}
|
|
233
|
+
while (remainingDenominator % 5n === 0n) {
|
|
234
|
+
remainingDenominator /= 5n;
|
|
235
|
+
fives++;
|
|
236
|
+
}
|
|
237
|
+
if (remainingDenominator !== 1n) {
|
|
238
|
+
return null;
|
|
239
|
+
}
|
|
240
|
+
const scale = Math.max(twos, fives);
|
|
241
|
+
return formatScaled(value.num * (pow10n(scale) / value.den), scale);
|
|
242
|
+
}
|
|
243
|
+
|
|
244
|
+
// Zero padding for the fraction digits, built once: indexing it is faster than padStart.
|
|
245
|
+
const ZPAD = Array.from({ length: 16 }, (_, length) => '0'.repeat(length));
|
|
246
|
+
|
|
247
|
+
/** Formats an integer at `scale` as a plain decimal string ("-0.05"). */
|
|
248
|
+
export function formatScaled(minor: number | bigint, scale: number): string {
|
|
249
|
+
if (typeof minor === 'number' && scale <= 15) {
|
|
250
|
+
if (scale === 0) {
|
|
251
|
+
return String(minor);
|
|
252
|
+
}
|
|
253
|
+
// integer/fraction split with exact integer arithmetic (the float quotient is corrected)
|
|
254
|
+
const magnitude = minor < 0 ? 0 - minor : minor;
|
|
255
|
+
const unit = POW10[scale]!;
|
|
256
|
+
if (magnitude + unit <= MAX_SAFE_MINOR) {
|
|
257
|
+
let whole = Math.floor(magnitude / unit);
|
|
258
|
+
let fraction = magnitude - whole * unit;
|
|
259
|
+
if (fraction < 0) {
|
|
260
|
+
whole -= 1;
|
|
261
|
+
fraction += unit;
|
|
262
|
+
} else if (fraction >= unit) {
|
|
263
|
+
whole += 1;
|
|
264
|
+
fraction -= unit;
|
|
265
|
+
}
|
|
266
|
+
let fractionDigits = String(fraction);
|
|
267
|
+
if (fractionDigits.length < scale) {
|
|
268
|
+
fractionDigits = ZPAD[scale - fractionDigits.length] + fractionDigits;
|
|
269
|
+
}
|
|
270
|
+
return (minor < 0 ? '-' : '') + whole + '.' + fractionDigits;
|
|
271
|
+
}
|
|
272
|
+
}
|
|
273
|
+
const neg = minor < 0;
|
|
274
|
+
let digits =
|
|
275
|
+
typeof minor === 'number' ? String(neg ? 0 - minor : minor) : (neg ? -minor : minor).toString();
|
|
276
|
+
if (scale > 0) {
|
|
277
|
+
if (digits.length <= scale) {
|
|
278
|
+
digits = '0'.repeat(scale - digits.length + 1) + digits;
|
|
279
|
+
}
|
|
280
|
+
digits = digits.slice(0, digits.length - scale) + '.' + digits.slice(digits.length - scale);
|
|
281
|
+
}
|
|
282
|
+
return neg ? '-' + digits : digits;
|
|
283
|
+
}
|