@ducatjs/money 0.0.0 → 0.2.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 +1034 -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 +520 -0
- package/data/checkout.json +230 -0
- package/data/cldr-cash.json +101 -0
- package/data/historic.json +78 -0
- package/data/iso4217-list-one.xml +1956 -0
- package/data/iso4217-list-three.xml +1185 -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 +140 -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/boc.d.ts +31 -0
- package/dist/boc.d.ts.map +1 -0
- package/dist/boc.js +114 -0
- package/dist/boc.js.map +1 -0
- package/dist/boe.d.ts +33 -0
- package/dist/boe.d.ts.map +1 -0
- package/dist/boe.js +114 -0
- package/dist/boe.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 +64 -0
- package/dist/cash.d.ts.map +1 -0
- package/dist/cash.js +134 -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 +52 -0
- package/dist/convert.d.ts.map +1 -0
- package/dist/convert.js +65 -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/drizzle/mysql.d.ts +105 -0
- package/dist/drizzle/mysql.d.ts.map +1 -0
- package/dist/drizzle/mysql.js +60 -0
- package/dist/drizzle/mysql.js.map +1 -0
- package/dist/drizzle/pg.d.ts +103 -0
- package/dist/drizzle/pg.d.ts.map +1 -0
- package/dist/drizzle/pg.js +60 -0
- package/dist/drizzle/pg.js.map +1 -0
- package/dist/drizzle/sqlite.d.ts +102 -0
- package/dist/drizzle/sqlite.d.ts.map +1 -0
- package/dist/drizzle/sqlite.js +59 -0
- package/dist/drizzle/sqlite.js.map +1 -0
- package/dist/ecb.d.ts +52 -0
- package/dist/ecb.d.ts.map +1 -0
- package/dist/ecb.js +285 -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/fed.d.ts +35 -0
- package/dist/fed.d.ts.map +1 -0
- package/dist/fed.js +134 -0
- package/dist/fed.js.map +1 -0
- package/dist/fetch.d.ts +103 -0
- package/dist/fetch.d.ts.map +1 -0
- package/dist/fetch.js +222 -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 +34 -0
- package/dist/fn.d.ts.map +1 -0
- package/dist/fn.js +37 -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 +14 -0
- package/dist/generated/cash.d.ts.map +1 -0
- package/dist/generated/cash.js +465 -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/historic.d.ts +337 -0
- package/dist/generated/historic.d.ts.map +1 -0
- package/dist/generated/historic.js +66 -0
- package/dist/generated/historic.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/historic.d.ts +40 -0
- package/dist/historic.d.ts.map +1 -0
- package/dist/historic.js +43 -0
- package/dist/historic.js.map +1 -0
- package/dist/history.d.ts +96 -0
- package/dist/history.d.ts.map +1 -0
- package/dist/history.js +213 -0
- package/dist/history.js.map +1 -0
- package/dist/hmrc.d.ts +28 -0
- package/dist/hmrc.d.ts.map +1 -0
- package/dist/hmrc.js +108 -0
- package/dist/hmrc.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/kysely.d.ts +120 -0
- package/dist/kysely.d.ts.map +1 -0
- package/dist/kysely.js +309 -0
- package/dist/kysely.js.map +1 -0
- package/dist/money.d.ts +302 -0
- package/dist/money.d.ts.map +1 -0
- package/dist/money.js +703 -0
- package/dist/money.js.map +1 -0
- package/dist/parse.d.ts +55 -0
- package/dist/parse.d.ts.map +1 -0
- package/dist/parse.js +419 -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/pg.d.ts +100 -0
- package/dist/pg.d.ts.map +1 -0
- package/dist/pg.js +343 -0
- package/dist/pg.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 +29 -0
- package/dist/plugins/all.d.ts.map +1 -0
- package/dist/plugins/all.js +30 -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 +19 -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 +20 -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/policy.d.ts +34 -0
- package/dist/policy.d.ts.map +1 -0
- package/dist/policy.js +90 -0
- package/dist/policy.js.map +1 -0
- package/dist/prisma.d.ts +77 -0
- package/dist/prisma.d.ts.map +1 -0
- package/dist/prisma.js +76 -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 +103 -0
- package/dist/provider.d.ts.map +1 -0
- package/dist/provider.js +280 -0
- package/dist/provider.js.map +1 -0
- package/dist/rate-text.d.ts +38 -0
- package/dist/rate-text.d.ts.map +1 -0
- package/dist/rate-text.js +143 -0
- package/dist/rate-text.js.map +1 -0
- package/dist/rate.d.ts +175 -0
- package/dist/rate.d.ts.map +1 -0
- package/dist/rate.js +371 -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/schema.d.ts +43 -0
- package/dist/schema.d.ts.map +1 -0
- package/dist/schema.js +77 -0
- package/dist/schema.js.map +1 -0
- package/dist/sql.d.ts +54 -0
- package/dist/sql.d.ts.map +1 -0
- package/dist/sql.js +131 -0
- package/dist/sql.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 +33 -0
- package/dist/tax.d.ts.map +1 -0
- package/dist/tax.js +55 -0
- package/dist/tax.js.map +1 -0
- package/dist/testing/arbitraries.d.ts +43 -0
- package/dist/testing/arbitraries.d.ts.map +1 -0
- package/dist/testing/arbitraries.js +98 -0
- package/dist/testing/arbitraries.js.map +1 -0
- package/dist/testing/index.d.ts +67 -0
- package/dist/testing/index.d.ts.map +1 -0
- package/dist/testing/index.js +159 -0
- package/dist/testing/index.js.map +1 -0
- package/dist/testing/jest.d.ts +2 -0
- package/dist/testing/jest.d.ts.map +1 -0
- package/dist/testing/jest.js +15 -0
- package/dist/testing/jest.js.map +1 -0
- package/dist/testing/vitest.d.ts +7 -0
- package/dist/testing/vitest.d.ts.map +1 -0
- package/dist/testing/vitest.js +12 -0
- package/dist/testing/vitest.js.map +1 -0
- package/dist/valibot.d.ts +33 -0
- package/dist/valibot.d.ts.map +1 -0
- package/dist/valibot.js +61 -0
- package/dist/valibot.js.map +1 -0
- package/dist/zod.d.ts +36 -0
- package/dist/zod.d.ts.map +1 -0
- package/dist/zod.js +58 -0
- package/dist/zod.js.map +1 -0
- package/package.json +280 -5
- package/src/adyen-fx.ts +175 -0
- package/src/adyen.ts +46 -0
- package/src/allocate.ts +393 -0
- package/src/bag.ts +170 -0
- package/src/boc.ts +136 -0
- package/src/boe.ts +131 -0
- package/src/braintree.ts +71 -0
- package/src/cash.ts +183 -0
- package/src/checkout.ts +77 -0
- package/src/convert.ts +177 -0
- package/src/currency.ts +61 -0
- package/src/decimal.ts +283 -0
- package/src/drizzle/mysql.ts +78 -0
- package/src/drizzle/pg.ts +78 -0
- package/src/drizzle/sqlite.ts +70 -0
- package/src/ecb.ts +328 -0
- package/src/exact.ts +182 -0
- package/src/fed.ts +146 -0
- package/src/fetch.ts +306 -0
- package/src/fixed.ts +558 -0
- package/src/fn.ts +94 -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 +478 -0
- package/src/generated/checkout.ts +151 -0
- package/src/generated/historic.ts +67 -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/historic.ts +77 -0
- package/src/history.ts +333 -0
- package/src/hmrc.ts +125 -0
- package/src/index.ts +41 -0
- package/src/klarna.ts +54 -0
- package/src/kysely.ts +588 -0
- package/src/money.ts +979 -0
- package/src/parse.ts +511 -0
- package/src/paypal.ts +93 -0
- package/src/pg.ts +410 -0
- package/src/plugins/adyen.ts +25 -0
- package/src/plugins/all.ts +57 -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 +49 -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 +40 -0
- package/src/policy.ts +124 -0
- package/src/prisma.ts +199 -0
- package/src/processor.ts +181 -0
- package/src/provider.ts +389 -0
- package/src/rate-text.ts +151 -0
- package/src/rate.ts +546 -0
- package/src/rounding-error.ts +8 -0
- package/src/rounding.ts +122 -0
- package/src/schema.ts +119 -0
- package/src/sql.ts +178 -0
- package/src/stripe-fx.ts +49 -0
- package/src/stripe.ts +69 -0
- package/src/tax.ts +102 -0
- package/src/testing/arbitraries.ts +134 -0
- package/src/testing/index.ts +247 -0
- package/src/testing/jest.ts +18 -0
- package/src/testing/vitest.ts +18 -0
- package/src/valibot.ts +87 -0
- package/src/zod.ts +78 -0
package/src/money.ts
ADDED
|
@@ -0,0 +1,979 @@
|
|
|
1
|
+
import { currencyExponent, type CurrencyCode } from './currency.js';
|
|
2
|
+
import {
|
|
3
|
+
formatScaled,
|
|
4
|
+
parseDecimal,
|
|
5
|
+
parsePlainDecimal,
|
|
6
|
+
POW10,
|
|
7
|
+
pow10n,
|
|
8
|
+
ratio,
|
|
9
|
+
normalizeMinor,
|
|
10
|
+
type Factor,
|
|
11
|
+
type Ratio,
|
|
12
|
+
} from './decimal.js';
|
|
13
|
+
import {
|
|
14
|
+
DEFAULT_ROUNDING,
|
|
15
|
+
divideAndRound,
|
|
16
|
+
divideAndRoundBigint,
|
|
17
|
+
RoundingError,
|
|
18
|
+
type RoundingMode,
|
|
19
|
+
} from './rounding.js';
|
|
20
|
+
|
|
21
|
+
// A module-local constant, not an import: the hot loops (sum, add) read it on every iteration, and
|
|
22
|
+
// V8 reads an imported binding through an extra indirection.
|
|
23
|
+
const MAX_SAFE_MINOR = Number.MAX_SAFE_INTEGER;
|
|
24
|
+
|
|
25
|
+
/** Currency codes accepted by constructors: known codes autocomplete, any string is allowed. */
|
|
26
|
+
export type CurrencyInput = CurrencyCode | (string & {});
|
|
27
|
+
|
|
28
|
+
/** The JSON form of Money: an exact decimal string in major units plus the currency code. */
|
|
29
|
+
export interface MoneyJSON<C extends string = string> {
|
|
30
|
+
/** Exact decimal string in major units, e.g. "12.34". */
|
|
31
|
+
readonly amount: string;
|
|
32
|
+
readonly currency: C;
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
/**
|
|
36
|
+
* A reusable rounding rule: a scale, an increment at that scale and a rounding mode, such as "CHF
|
|
37
|
+
* cash" (scale 2, increment 5, half up) or "4 decimals, half even". Build one with `roundingPolicy()`
|
|
38
|
+
* from `@ducatjs/money/policy` (or `cashPolicy()` from `@ducatjs/money/cash`) and pass it wherever
|
|
39
|
+
* a rounding mode is accepted: `m.multiply('1.075', policy)`, `m.round(policy)`. A policy is also
|
|
40
|
+
* a function that rounds an amount, so `m.with(policy)` and `amounts.map(policy)` work too.
|
|
41
|
+
*
|
|
42
|
+
* Policies are plain values passed explicitly; they are never stored on amounts or set globally.
|
|
43
|
+
*/
|
|
44
|
+
export interface RoundingPolicy {
|
|
45
|
+
/** Rounds `money` to this policy (exactly like `round(money, policy)`). */
|
|
46
|
+
<C extends string>(money: Money<C>): Money<C>;
|
|
47
|
+
/** Decimal places of the result; `undefined` means the currency's ISO exponent. */
|
|
48
|
+
readonly scale: number | undefined;
|
|
49
|
+
/** The result is a multiple of this many 10^-scale units (1 for plain rounding, 5 for 0.05). */
|
|
50
|
+
readonly increment: number;
|
|
51
|
+
/** How to round to the increment. */
|
|
52
|
+
readonly rounding: RoundingMode;
|
|
53
|
+
/** The one currency the policy is for, if any; other currencies throw `CurrencyMismatchError`. */
|
|
54
|
+
readonly currency: string | undefined;
|
|
55
|
+
/**
|
|
56
|
+
* @internal money × factor, rounded once to this policy, under a key only this copy of the
|
|
57
|
+
* package can build. The core calls it for every operation given a policy, so the policy code
|
|
58
|
+
* stays out of bundles that never build one.
|
|
59
|
+
*/
|
|
60
|
+
readonly [ROUND_PRODUCT]: <C extends string>(money: Money<C>, factor: Ratio) => Money<C>;
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
/**
|
|
64
|
+
* @internal The key a policy's rounding function is stored under. Module-private, so only
|
|
65
|
+
* `roundingPolicy` from this copy of the package makes values the core accepts as policies: a
|
|
66
|
+
* lookalike function, or a policy from a second installed copy (whose results would be that copy's
|
|
67
|
+
* Money), is rejected with a TypeError, as `isMoney` rejects the other copy's Money.
|
|
68
|
+
*/
|
|
69
|
+
export const ROUND_PRODUCT: unique symbol = Symbol();
|
|
70
|
+
|
|
71
|
+
/**
|
|
72
|
+
* @internal money × factor rounded by a policy. Anything not built by `roundingPolicy` lacks the
|
|
73
|
+
* private key, so calling it throws a TypeError; that is the whole check, kept this small because
|
|
74
|
+
* it is in every bundle.
|
|
75
|
+
*/
|
|
76
|
+
export const roundWithPolicy = <C extends string>(
|
|
77
|
+
money: Money<C>,
|
|
78
|
+
factor: Ratio,
|
|
79
|
+
policy: RoundingPolicy,
|
|
80
|
+
): Money<C> => policy[ROUND_PRODUCT](money, factor);
|
|
81
|
+
|
|
82
|
+
/** What rounding parameters accept: a mode such as `'halfEven'`, or a `RoundingPolicy`. */
|
|
83
|
+
export type RoundingInput = RoundingMode | RoundingPolicy;
|
|
84
|
+
|
|
85
|
+
/** Thrown when two amounts in different currencies are combined. */
|
|
86
|
+
export class CurrencyMismatchError extends TypeError {
|
|
87
|
+
override name = 'CurrencyMismatchError';
|
|
88
|
+
declare readonly expected: string;
|
|
89
|
+
declare readonly actual: string;
|
|
90
|
+
constructor(expected: string, actual: string) {
|
|
91
|
+
super(`Currency mismatch: ${expected} vs ${actual}`);
|
|
92
|
+
this.expected = expected;
|
|
93
|
+
this.actual = actual;
|
|
94
|
+
}
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
/**
|
|
98
|
+
* An immutable amount of money: an integer number of 10^-scale units of `currency`.
|
|
99
|
+
*
|
|
100
|
+
* `minor` is a JS number whenever it is a safe integer (|v| <= 2^53 - 1) and a bigint otherwise, so
|
|
101
|
+
* ordinary amounts never allocate a bigint, and huge or high-precision amounts never lose a digit.
|
|
102
|
+
* `scale` is normally the currency's ISO exponent (2 for EUR) but can be larger for sub-minor
|
|
103
|
+
* precision (unit prices, FX intermediates); `round()` brings it back.
|
|
104
|
+
*
|
|
105
|
+
* Instances are not frozen (Object.freeze costs 5-8x on construction in V8 and JSC; see bench/),
|
|
106
|
+
* but every field is readonly and no operation mutates. Create values with `money()` /
|
|
107
|
+
* `fromMinor()`.
|
|
108
|
+
*
|
|
109
|
+
* The class carries the core methods only. Opt-in modules (`@ducatjs/money/allocate`,
|
|
110
|
+
* `@ducatjs/money/tax`, `@ducatjs/money/format`, ...) add theirs when imported; see `extendMoney`.
|
|
111
|
+
*/
|
|
112
|
+
class Money<C extends string = string> {
|
|
113
|
+
declare readonly currency: C;
|
|
114
|
+
declare readonly minor: number | bigint;
|
|
115
|
+
declare readonly scale: number;
|
|
116
|
+
/** @internal */
|
|
117
|
+
constructor(currency: C, minor: number | bigint, scale: number) {
|
|
118
|
+
this.currency = currency;
|
|
119
|
+
this.minor = minor;
|
|
120
|
+
this.scale = scale;
|
|
121
|
+
}
|
|
122
|
+
/** "12.34 EUR" */
|
|
123
|
+
toString(): string {
|
|
124
|
+
return `${formatScaled(this.minor, this.scale)} ${this.currency}`;
|
|
125
|
+
}
|
|
126
|
+
toJSON(): MoneyJSON<C> {
|
|
127
|
+
return { amount: formatScaled(this.minor, this.scale), currency: this.currency };
|
|
128
|
+
}
|
|
129
|
+
/** Blocks `a + b`, `a > b`, `+a`: arithmetic and comparison must go through the library. */
|
|
130
|
+
[Symbol.toPrimitive](hint: string): string {
|
|
131
|
+
if (hint === 'string') {
|
|
132
|
+
return this.toString();
|
|
133
|
+
}
|
|
134
|
+
throw new TypeError(
|
|
135
|
+
'Money cannot be converted to a number; use add(), compare(), toDecimal() etc.',
|
|
136
|
+
);
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
// Methods. Each one is a thin wrapper over the free function of the same name (also exported), so
|
|
140
|
+
// `a.add(b)` and `add(a, b)` are the same code. Operands are Money only: a bare number is never
|
|
141
|
+
// guessed to mean major or minor units.
|
|
142
|
+
|
|
143
|
+
// arithmetic
|
|
144
|
+
/** this + other (same currency; any scale) */
|
|
145
|
+
add(other: Money<C>): Money<C> {
|
|
146
|
+
return add(this, other);
|
|
147
|
+
}
|
|
148
|
+
/** this - other */
|
|
149
|
+
subtract(other: Money<C>): Money<C> {
|
|
150
|
+
return subtract(this, other);
|
|
151
|
+
}
|
|
152
|
+
/**
|
|
153
|
+
* this * factor, rounded to this scale. `factor` is exact: integer, decimal string ('1.075'),
|
|
154
|
+
* bigint or ratio().
|
|
155
|
+
*/
|
|
156
|
+
multiply(factor: Factor, rounding?: RoundingInput): Money<C> {
|
|
157
|
+
return multiply(this, factor, rounding);
|
|
158
|
+
}
|
|
159
|
+
/** this / divisor, rounded to this scale (or to a policy's scale and increment) */
|
|
160
|
+
divide(divisor: Factor, rounding?: RoundingInput): Money<C> {
|
|
161
|
+
return divide(this, divisor, rounding);
|
|
162
|
+
}
|
|
163
|
+
negate(): Money<C> {
|
|
164
|
+
return negate(this);
|
|
165
|
+
}
|
|
166
|
+
abs(): Money<C> {
|
|
167
|
+
return abs(this);
|
|
168
|
+
}
|
|
169
|
+
/** Rounds to the currency's exponent (or `scale`), or to a rounding policy. */
|
|
170
|
+
round(rounding: RoundingMode, scale?: number): Money<C>;
|
|
171
|
+
round(policy: RoundingPolicy): Money<C>;
|
|
172
|
+
round(rounding: RoundingInput, scale?: number): Money<C> {
|
|
173
|
+
// the free function handles both; the cast only picks its implementation signature
|
|
174
|
+
return round(this, rounding as RoundingMode, scale);
|
|
175
|
+
}
|
|
176
|
+
/** Changes the scale; decreasing it rounds (default 'halfExpand'). */
|
|
177
|
+
toScale(scale: number, rounding?: RoundingMode): Money<C> {
|
|
178
|
+
return toScale(this, scale, rounding);
|
|
179
|
+
}
|
|
180
|
+
// comparison
|
|
181
|
+
/** -1, 0 or 1; throws on currency mismatch */
|
|
182
|
+
compare(other: Money<C>): -1 | 0 | 1 {
|
|
183
|
+
return compare(this, other);
|
|
184
|
+
}
|
|
185
|
+
/** same currency and value; a different currency is simply not equal */
|
|
186
|
+
equals(other: Money): boolean {
|
|
187
|
+
return equals(this, other);
|
|
188
|
+
}
|
|
189
|
+
lessThan(other: Money<C>): boolean {
|
|
190
|
+
return compare(this, other) < 0;
|
|
191
|
+
}
|
|
192
|
+
lessThanOrEqual(other: Money<C>): boolean {
|
|
193
|
+
return compare(this, other) <= 0;
|
|
194
|
+
}
|
|
195
|
+
greaterThan(other: Money<C>): boolean {
|
|
196
|
+
return compare(this, other) > 0;
|
|
197
|
+
}
|
|
198
|
+
greaterThanOrEqual(other: Money<C>): boolean {
|
|
199
|
+
return compare(this, other) >= 0;
|
|
200
|
+
}
|
|
201
|
+
isZero(): boolean {
|
|
202
|
+
return this.minor == 0;
|
|
203
|
+
}
|
|
204
|
+
isPositive(): boolean {
|
|
205
|
+
return this.minor > 0;
|
|
206
|
+
}
|
|
207
|
+
isNegative(): boolean {
|
|
208
|
+
return this.minor < 0;
|
|
209
|
+
}
|
|
210
|
+
sign(): -1 | 0 | 1 {
|
|
211
|
+
return sign(this);
|
|
212
|
+
}
|
|
213
|
+
min(...others: Money<C>[]): Money<C> {
|
|
214
|
+
return min(this, ...others);
|
|
215
|
+
}
|
|
216
|
+
max(...others: Money<C>[]): Money<C> {
|
|
217
|
+
return max(this, ...others);
|
|
218
|
+
}
|
|
219
|
+
clamp(lo: Money<C>, hi: Money<C>): Money<C> {
|
|
220
|
+
return clamp(this, lo, hi);
|
|
221
|
+
}
|
|
222
|
+
|
|
223
|
+
/** Same currency, value and scale: 1.0 EUR is not identical to 1.00 EUR. */
|
|
224
|
+
identical(other: Money): boolean {
|
|
225
|
+
return identical(this, other);
|
|
226
|
+
}
|
|
227
|
+
/**
|
|
228
|
+
* Applies `operation` to this amount and returns its result, so a rounding policy or a
|
|
229
|
+
* conversion reads as one step in a chain: `price.multiply('1.075').with(toCash)`.
|
|
230
|
+
*/
|
|
231
|
+
with<R>(operation: (money: Money<C>) => R): R {
|
|
232
|
+
return operation(this);
|
|
233
|
+
}
|
|
234
|
+
|
|
235
|
+
// output
|
|
236
|
+
/** The whole major units, truncated toward zero: 12 for 12.34 EUR, -12 for -12.34 EUR. */
|
|
237
|
+
majorPart(): number | bigint {
|
|
238
|
+
return majorPart(this);
|
|
239
|
+
}
|
|
240
|
+
/** The rest in 10^-scale units, with the amount's sign: 34 for 12.34 EUR, -34 for -12.34. */
|
|
241
|
+
minorPart(): number | bigint {
|
|
242
|
+
return minorPart(this);
|
|
243
|
+
}
|
|
244
|
+
/** Exact decimal string in major units: "12.34" */
|
|
245
|
+
toDecimal(): string {
|
|
246
|
+
return formatScaled(this.minor, this.scale);
|
|
247
|
+
}
|
|
248
|
+
/** Minor units as a bigint (BIGINT columns) */
|
|
249
|
+
toMinor(): bigint {
|
|
250
|
+
return toBigInt(this.minor);
|
|
251
|
+
}
|
|
252
|
+
/** Minor units as a number; throws beyond 2^53 */
|
|
253
|
+
toMinorNumber(): number {
|
|
254
|
+
return toMinorNumber(this);
|
|
255
|
+
}
|
|
256
|
+
}
|
|
257
|
+
export type { Money };
|
|
258
|
+
|
|
259
|
+
/** Whether a value is a Money from this package. */
|
|
260
|
+
export function isMoney(value: unknown): value is Money {
|
|
261
|
+
return value instanceof Money;
|
|
262
|
+
}
|
|
263
|
+
|
|
264
|
+
/**
|
|
265
|
+
* Whether a value is a Money in `currency`. It narrows a currency known only at run time
|
|
266
|
+
* (`Money<string>`, or `unknown`) to the literal type:
|
|
267
|
+
*
|
|
268
|
+
* if (isMoneyIn(price, 'EUR')) { price.add(money('1', 'EUR')) }
|
|
269
|
+
*/
|
|
270
|
+
export function isMoneyIn<C extends CurrencyInput>(value: unknown, currency: C): value is Money<C> {
|
|
271
|
+
return value instanceof Money && value.currency === currency;
|
|
272
|
+
}
|
|
273
|
+
|
|
274
|
+
/**
|
|
275
|
+
* Narrows `money` to `Money<C>`, or throws a `CurrencyMismatchError` if it is in another
|
|
276
|
+
* currency. Use it where a different currency is a bug rather than a branch.
|
|
277
|
+
*/
|
|
278
|
+
export function assertCurrency<C extends CurrencyInput>(
|
|
279
|
+
money: Money,
|
|
280
|
+
currency: C,
|
|
281
|
+
): asserts money is Money<C> {
|
|
282
|
+
// A non-Money would otherwise pass when it happens to have a matching `currency` field.
|
|
283
|
+
if (!(money instanceof Money)) {
|
|
284
|
+
throw new TypeError(`Expected Money, got ${typeof money}`);
|
|
285
|
+
}
|
|
286
|
+
if (money.currency !== currency) {
|
|
287
|
+
throw new CurrencyMismatchError(currency, money.currency);
|
|
288
|
+
}
|
|
289
|
+
}
|
|
290
|
+
|
|
291
|
+
/**
|
|
292
|
+
* Which module installed each added method, so a second copy of the same module can replace its
|
|
293
|
+
* own.
|
|
294
|
+
*/
|
|
295
|
+
const methodOwners = new Map<string, string>();
|
|
296
|
+
|
|
297
|
+
/**
|
|
298
|
+
* Names `extendMoney` refuses: the ones every object inherits, whose meaning other code relies on.
|
|
299
|
+
* `toLocaleString` is allowed, since a formatting module may want to provide it.
|
|
300
|
+
*/
|
|
301
|
+
const RESERVED_NAMES = new Set(
|
|
302
|
+
Object.getOwnPropertyNames(Object.prototype).filter((name) => name !== 'toLocaleString'),
|
|
303
|
+
);
|
|
304
|
+
|
|
305
|
+
/** Options for `extendMoney`. */
|
|
306
|
+
export interface ExtendMoneyOptions {
|
|
307
|
+
/**
|
|
308
|
+
* Who is installing the methods, e.g. '@ducatjs/money/allocate'. Installing again under the same
|
|
309
|
+
* owner replaces that owner's methods, which happens when a module is loaded twice (hot reload,
|
|
310
|
+
* two copies of the package). Without an owner, or under a different one, an existing name
|
|
311
|
+
* throws.
|
|
312
|
+
*/
|
|
313
|
+
readonly owner?: string;
|
|
314
|
+
}
|
|
315
|
+
|
|
316
|
+
/**
|
|
317
|
+
* Adds methods to every Money (this is how `@ducatjs/money/allocate`, `@ducatjs/money/format`, ...
|
|
318
|
+
* install theirs). Declare their types with `declare module '@ducatjs/money' { interface Money<C
|
|
319
|
+
* extends string> { ... } }`. The methods are non-enumerable, like class methods. A name that Money
|
|
320
|
+
* already has (one of its own methods, or one added by a different owner) throws, so two modules
|
|
321
|
+
* cannot silently fight over it.
|
|
322
|
+
*/
|
|
323
|
+
export function extendMoney(
|
|
324
|
+
methods: Record<string, (this: Money, ...args: never[]) => unknown>,
|
|
325
|
+
options?: ExtendMoneyOptions,
|
|
326
|
+
): void {
|
|
327
|
+
const prototype = Money.prototype as unknown as Record<string, unknown>;
|
|
328
|
+
const owner = options?.owner;
|
|
329
|
+
|
|
330
|
+
for (const name of Object.keys(methods)) {
|
|
331
|
+
const method = methods[name];
|
|
332
|
+
|
|
333
|
+
if (RESERVED_NAMES.has(name)) {
|
|
334
|
+
throw new TypeError(`Money#${name} is reserved`);
|
|
335
|
+
}
|
|
336
|
+
|
|
337
|
+
// Replacing an existing method would silently change behaviour for every caller, unless it is
|
|
338
|
+
// the same function or the same owner installing its own methods again.
|
|
339
|
+
const previousOwner = methodOwners.get(name);
|
|
340
|
+
const isOwnReinstall = owner !== undefined && previousOwner === owner;
|
|
341
|
+
if (Object.hasOwn(prototype, name) && prototype[name] !== method && !isOwnReinstall) {
|
|
342
|
+
throw new TypeError(`Money#${name} is already defined`);
|
|
343
|
+
}
|
|
344
|
+
|
|
345
|
+
// Non-enumerable, like the class's own methods, so Object.keys and spreads see only the fields.
|
|
346
|
+
Object.defineProperty(prototype, name, {
|
|
347
|
+
value: method,
|
|
348
|
+
writable: true,
|
|
349
|
+
configurable: true,
|
|
350
|
+
enumerable: false,
|
|
351
|
+
});
|
|
352
|
+
if (owner !== undefined) {
|
|
353
|
+
methodOwners.set(name, owner);
|
|
354
|
+
}
|
|
355
|
+
}
|
|
356
|
+
}
|
|
357
|
+
|
|
358
|
+
/** @internal construct from a value that may be an unsafe bigint */
|
|
359
|
+
export function make<C extends string>(
|
|
360
|
+
currency: C,
|
|
361
|
+
minor: number | bigint,
|
|
362
|
+
scale: number,
|
|
363
|
+
): Money<C> {
|
|
364
|
+
return new Money(currency, typeof minor === 'bigint' ? normalizeMinor(minor) : minor, scale);
|
|
365
|
+
}
|
|
366
|
+
|
|
367
|
+
const toBigInt = (minor: number | bigint) => (typeof minor === 'bigint' ? minor : BigInt(minor));
|
|
368
|
+
|
|
369
|
+
/** v * 10^e exactly (e >= 0) */
|
|
370
|
+
export function scaleUp(minor: number | bigint, exponent: number): number | bigint {
|
|
371
|
+
if (exponent === 0) {
|
|
372
|
+
return minor;
|
|
373
|
+
}
|
|
374
|
+
if (typeof minor === 'number' && exponent <= 15) {
|
|
375
|
+
const scaled = minor * POW10[exponent]!;
|
|
376
|
+
if (scaled <= MAX_SAFE_MINOR && scaled >= -MAX_SAFE_MINOR) {
|
|
377
|
+
return scaled;
|
|
378
|
+
}
|
|
379
|
+
}
|
|
380
|
+
return normalizeMinor(toBigInt(minor) * pow10n(exponent));
|
|
381
|
+
}
|
|
382
|
+
|
|
383
|
+
/** v / 10^e rounded (e >= 0) */
|
|
384
|
+
export function scaleDown(
|
|
385
|
+
minor: number | bigint,
|
|
386
|
+
exponent: number,
|
|
387
|
+
mode: RoundingMode,
|
|
388
|
+
): number | bigint {
|
|
389
|
+
if (exponent === 0) {
|
|
390
|
+
return minor;
|
|
391
|
+
}
|
|
392
|
+
if (typeof minor === 'number' && exponent <= 15) {
|
|
393
|
+
return divideAndRound(minor, POW10[exponent]!, mode);
|
|
394
|
+
}
|
|
395
|
+
return normalizeMinor(divideAndRoundBigint(toBigInt(minor), pow10n(exponent), mode));
|
|
396
|
+
}
|
|
397
|
+
|
|
398
|
+
// ---------------------------------------------------------------------------------------------
|
|
399
|
+
// Construction
|
|
400
|
+
// ---------------------------------------------------------------------------------------------
|
|
401
|
+
|
|
402
|
+
/** Options for `money()` and `fromJSON()`: the scale to keep and how to round extra decimals. */
|
|
403
|
+
export interface MoneyOptions {
|
|
404
|
+
/** Decimal places to keep (default: the currency's exponent). */
|
|
405
|
+
readonly scale?: number;
|
|
406
|
+
/** How to round input with more decimals than `scale` (default 'unnecessary': throw). */
|
|
407
|
+
readonly rounding?: RoundingMode;
|
|
408
|
+
}
|
|
409
|
+
|
|
410
|
+
/**
|
|
411
|
+
* Creates money from an amount in major units.
|
|
412
|
+
*
|
|
413
|
+
* money('12.34', 'EUR') // exact decimal string: the recommended form
|
|
414
|
+
* money(12, 'EUR') // integers are major units: 12.00 EUR
|
|
415
|
+
* money(12.34, 'EUR') // non-integer numbers are read at their shortest decimal form ("12.34")
|
|
416
|
+
* money(10n ** 30n, 'USD')
|
|
417
|
+
*
|
|
418
|
+
* Throws if the amount has more decimals than the currency (or `scale`) unless `rounding` is given,
|
|
419
|
+
* so `money(0.1 + 0.2, 'EUR')` throws rather than silently becoming 0.30.
|
|
420
|
+
*/
|
|
421
|
+
export function money<C extends CurrencyInput>(
|
|
422
|
+
amount: string | number | bigint,
|
|
423
|
+
currency: C,
|
|
424
|
+
options?: MoneyOptions,
|
|
425
|
+
): Money<C> {
|
|
426
|
+
const scale = options?.scale ?? currencyExponent(currency);
|
|
427
|
+
if (typeof amount === 'string') {
|
|
428
|
+
const parsed = parsePlainDecimal(amount) ?? parseDecimal(amount);
|
|
429
|
+
return fromScaled(
|
|
430
|
+
currency,
|
|
431
|
+
parsed.digits,
|
|
432
|
+
parsed.scale,
|
|
433
|
+
scale,
|
|
434
|
+
options?.rounding ?? 'unnecessary',
|
|
435
|
+
amount,
|
|
436
|
+
);
|
|
437
|
+
}
|
|
438
|
+
if (typeof amount === 'number') {
|
|
439
|
+
if (Number.isSafeInteger(amount)) {
|
|
440
|
+
return make(currency, scaleUp(amount, scale), scale);
|
|
441
|
+
}
|
|
442
|
+
if (!Number.isFinite(amount)) {
|
|
443
|
+
throw new RangeError(`Invalid amount ${amount}`);
|
|
444
|
+
}
|
|
445
|
+
const parsed = parseDecimal(String(amount));
|
|
446
|
+
return fromScaled(
|
|
447
|
+
currency,
|
|
448
|
+
parsed.digits,
|
|
449
|
+
parsed.scale,
|
|
450
|
+
scale,
|
|
451
|
+
options?.rounding ?? 'unnecessary',
|
|
452
|
+
amount,
|
|
453
|
+
);
|
|
454
|
+
}
|
|
455
|
+
if (typeof amount === 'bigint') {
|
|
456
|
+
return make(currency, scaleUp(normalizeMinor(amount), scale), scale);
|
|
457
|
+
}
|
|
458
|
+
throw new TypeError(`Invalid amount ${String(amount)}`);
|
|
459
|
+
}
|
|
460
|
+
|
|
461
|
+
function fromScaled<C extends string>(
|
|
462
|
+
currency: C,
|
|
463
|
+
digits: number | bigint,
|
|
464
|
+
from: number,
|
|
465
|
+
to: number,
|
|
466
|
+
mode: RoundingMode,
|
|
467
|
+
input: unknown,
|
|
468
|
+
): Money<C> {
|
|
469
|
+
if (typeof digits === 'bigint') {
|
|
470
|
+
digits = normalizeMinor(digits);
|
|
471
|
+
}
|
|
472
|
+
if (from === to) {
|
|
473
|
+
return new Money(currency, digits, to);
|
|
474
|
+
}
|
|
475
|
+
if (from < to) {
|
|
476
|
+
return make(currency, scaleUp(digits, to - from), to);
|
|
477
|
+
}
|
|
478
|
+
try {
|
|
479
|
+
return make(currency, scaleDown(digits, from - to, mode), to);
|
|
480
|
+
} catch (error) {
|
|
481
|
+
if (error instanceof RoundingError) {
|
|
482
|
+
throw new RoundingError(
|
|
483
|
+
`${String(input)} has more than ${to} decimal places for ${currency}; pass { rounding } or { scale }`,
|
|
484
|
+
);
|
|
485
|
+
}
|
|
486
|
+
throw error;
|
|
487
|
+
}
|
|
488
|
+
}
|
|
489
|
+
|
|
490
|
+
/**
|
|
491
|
+
* Creates money from an integer count of minor units (cents): `fromMinor(1234, 'EUR')` is 12.34
|
|
492
|
+
* EUR. This is the form to read from a BIGINT column or a payment processor (but see
|
|
493
|
+
* `stripe`/`adyen` for processors whose exponent differs from ISO).
|
|
494
|
+
*/
|
|
495
|
+
export function fromMinor<C extends CurrencyInput>(
|
|
496
|
+
minor: number | bigint,
|
|
497
|
+
currency: C,
|
|
498
|
+
scale?: number,
|
|
499
|
+
): Money<C> {
|
|
500
|
+
const resolvedScale = scale ?? currencyExponent(currency);
|
|
501
|
+
if (typeof minor === 'number') {
|
|
502
|
+
if (!Number.isSafeInteger(minor)) {
|
|
503
|
+
throw new RangeError(`Minor units must be a safe integer, got ${minor}; pass a bigint`);
|
|
504
|
+
}
|
|
505
|
+
return new Money(currency, minor + 0, resolvedScale);
|
|
506
|
+
}
|
|
507
|
+
if (typeof minor !== 'bigint') {
|
|
508
|
+
throw new TypeError(`Invalid minor units ${String(minor)}`);
|
|
509
|
+
}
|
|
510
|
+
return make(currency, minor, resolvedScale);
|
|
511
|
+
}
|
|
512
|
+
|
|
513
|
+
/** Zero in a currency, at its exponent (or `scale`). */
|
|
514
|
+
export function zero<C extends CurrencyInput>(currency: C, scale?: number): Money<C> {
|
|
515
|
+
return new Money(currency, 0, scale ?? currencyExponent(currency));
|
|
516
|
+
}
|
|
517
|
+
|
|
518
|
+
// ---------------------------------------------------------------------------------------------
|
|
519
|
+
// Arithmetic
|
|
520
|
+
// ---------------------------------------------------------------------------------------------
|
|
521
|
+
|
|
522
|
+
function mismatch(money: Money, other: Money): never {
|
|
523
|
+
throw new CurrencyMismatchError(money.currency, other.currency);
|
|
524
|
+
}
|
|
525
|
+
|
|
526
|
+
function addUsingBigInt<C extends string>(money: Money<C>, other: Money, sign: 1 | -1): Money<C> {
|
|
527
|
+
const scale = Math.max(money.scale, other.scale);
|
|
528
|
+
const left = toBigInt(scaleUp(money.minor, scale - money.scale));
|
|
529
|
+
const right = toBigInt(scaleUp(other.minor, scale - other.scale));
|
|
530
|
+
return make(money.currency, sign === 1 ? left + right : left - right, scale);
|
|
531
|
+
}
|
|
532
|
+
|
|
533
|
+
/**
|
|
534
|
+
* a + b. Mixing currencies is a type error for literal currency types and a runtime error
|
|
535
|
+
* otherwise.
|
|
536
|
+
*/
|
|
537
|
+
export function add<C extends string>(money: Money<C>, other: Money<NoInfer<C>>): Money<C> {
|
|
538
|
+
if (money.currency !== other.currency) {
|
|
539
|
+
mismatch(money, other);
|
|
540
|
+
}
|
|
541
|
+
const left = money.minor;
|
|
542
|
+
const right = other.minor;
|
|
543
|
+
if (typeof left === 'number' && typeof right === 'number' && money.scale === other.scale) {
|
|
544
|
+
// exact whenever |sum| <= MAX_SAFE_MINOR: both inputs are safe integers
|
|
545
|
+
const sum = left + right;
|
|
546
|
+
if (sum <= MAX_SAFE_MINOR && sum >= -MAX_SAFE_MINOR) {
|
|
547
|
+
return new Money(money.currency, sum, money.scale);
|
|
548
|
+
}
|
|
549
|
+
}
|
|
550
|
+
return addUsingBigInt(money, other, 1);
|
|
551
|
+
}
|
|
552
|
+
|
|
553
|
+
/** a - b */
|
|
554
|
+
export function subtract<C extends string>(money: Money<C>, other: Money<NoInfer<C>>): Money<C> {
|
|
555
|
+
if (money.currency !== other.currency) {
|
|
556
|
+
mismatch(money, other);
|
|
557
|
+
}
|
|
558
|
+
const left = money.minor;
|
|
559
|
+
const right = other.minor;
|
|
560
|
+
if (typeof left === 'number' && typeof right === 'number' && money.scale === other.scale) {
|
|
561
|
+
const difference = left - right;
|
|
562
|
+
if (difference <= MAX_SAFE_MINOR && difference >= -MAX_SAFE_MINOR) {
|
|
563
|
+
return new Money(money.currency, difference + 0, money.scale);
|
|
564
|
+
}
|
|
565
|
+
}
|
|
566
|
+
return addUsingBigInt(money, other, -1);
|
|
567
|
+
}
|
|
568
|
+
|
|
569
|
+
type IsUnion<T, U = T> = T extends unknown ? ([U] extends [T] ? false : true) : never;
|
|
570
|
+
/**
|
|
571
|
+
* Rejects arrays whose element type mixes several literal currencies, e.g. (Money<'EUR'> |
|
|
572
|
+
* Money<'USD'>)[].
|
|
573
|
+
*/
|
|
574
|
+
type SingleCurrency<C extends string> =
|
|
575
|
+
true extends IsUnion<C> ? { readonly 'mixed currencies are not allowed': C } : unknown;
|
|
576
|
+
|
|
577
|
+
/** Sum of a list (same currency; any scale). An empty list needs `currency` and returns zero. */
|
|
578
|
+
export function sum<C extends string>(
|
|
579
|
+
items: readonly Money<C>[] & SingleCurrency<C>,
|
|
580
|
+
currency?: NoInfer<C>,
|
|
581
|
+
): Money<C> {
|
|
582
|
+
const count = items.length;
|
|
583
|
+
if (count === 0) {
|
|
584
|
+
if (currency === undefined) {
|
|
585
|
+
throw new RangeError('sum() of an empty list needs a currency');
|
|
586
|
+
}
|
|
587
|
+
return zero(currency);
|
|
588
|
+
}
|
|
589
|
+
|
|
590
|
+
let total = items[0]!;
|
|
591
|
+
if (currency !== undefined && total.currency !== currency) {
|
|
592
|
+
throw new CurrencyMismatchError(currency, total.currency);
|
|
593
|
+
}
|
|
594
|
+
const itemCurrency = total.currency;
|
|
595
|
+
const scale = total.scale;
|
|
596
|
+
|
|
597
|
+
// Fast loop on plain numbers: each partial sum of safe integers is exact while it stays within
|
|
598
|
+
// MAX_SAFE_MINOR. It falls back to add() at the first bigint, scale change or overflow. NaN marks
|
|
599
|
+
// "no fast total".
|
|
600
|
+
let fastTotal = typeof total.minor === 'number' ? total.minor : NaN;
|
|
601
|
+
let i = 1;
|
|
602
|
+
for (; i < count && fastTotal === fastTotal; i++) {
|
|
603
|
+
const item = items[i]!;
|
|
604
|
+
if (item.currency !== itemCurrency) {
|
|
605
|
+
mismatch(total, item);
|
|
606
|
+
}
|
|
607
|
+
if (typeof item.minor !== 'number' || item.scale !== scale) {
|
|
608
|
+
break;
|
|
609
|
+
}
|
|
610
|
+
const next = fastTotal + item.minor;
|
|
611
|
+
if (!(next <= MAX_SAFE_MINOR && next >= -MAX_SAFE_MINOR)) {
|
|
612
|
+
break;
|
|
613
|
+
}
|
|
614
|
+
fastTotal = next;
|
|
615
|
+
}
|
|
616
|
+
if (fastTotal === fastTotal) {
|
|
617
|
+
total = new Money(itemCurrency, fastTotal, scale);
|
|
618
|
+
}
|
|
619
|
+
|
|
620
|
+
for (; i < count; i++) {
|
|
621
|
+
total = add(total, items[i]!);
|
|
622
|
+
}
|
|
623
|
+
return total;
|
|
624
|
+
}
|
|
625
|
+
|
|
626
|
+
/** -money */
|
|
627
|
+
export function negate<C extends string>(money: Money<C>): Money<C> {
|
|
628
|
+
const minor = money.minor;
|
|
629
|
+
return new Money(
|
|
630
|
+
money.currency,
|
|
631
|
+
typeof minor === 'number' ? 0 - minor : normalizeMinor(-minor),
|
|
632
|
+
money.scale,
|
|
633
|
+
);
|
|
634
|
+
}
|
|
635
|
+
|
|
636
|
+
/** |money| */
|
|
637
|
+
export function abs<C extends string>(money: Money<C>): Money<C> {
|
|
638
|
+
return money.minor < 0 ? negate(money) : money;
|
|
639
|
+
}
|
|
640
|
+
|
|
641
|
+
/**
|
|
642
|
+
* m * factor, rounded to m's scale. `factor` is exact: an integer, a decimal string ('1.075'), a
|
|
643
|
+
* bigint, or a `ratio()`. Rounding defaults to 'halfExpand' (ties away from zero); pass
|
|
644
|
+
* 'unnecessary' to throw instead.
|
|
645
|
+
*/
|
|
646
|
+
export function multiply<C extends string>(
|
|
647
|
+
money: Money<C>,
|
|
648
|
+
factor: Factor,
|
|
649
|
+
rounding: RoundingInput = DEFAULT_ROUNDING,
|
|
650
|
+
): Money<C> {
|
|
651
|
+
const minor = money.minor;
|
|
652
|
+
// An integer product is exact at this scale, but a policy may ask for another scale or increment.
|
|
653
|
+
if (
|
|
654
|
+
typeof factor === 'number' &&
|
|
655
|
+
Number.isSafeInteger(factor) &&
|
|
656
|
+
typeof minor === 'number' &&
|
|
657
|
+
typeof rounding === 'string'
|
|
658
|
+
) {
|
|
659
|
+
const product = minor * factor;
|
|
660
|
+
if (product <= MAX_SAFE_MINOR && product >= -MAX_SAFE_MINOR) {
|
|
661
|
+
return new Money(money.currency, product + 0, money.scale);
|
|
662
|
+
}
|
|
663
|
+
}
|
|
664
|
+
return multiplyByRatio(money, ratio(factor), rounding);
|
|
665
|
+
}
|
|
666
|
+
|
|
667
|
+
/** @internal m * r, rounded with a mode (at `scale`) or with a policy (at the policy's scale) */
|
|
668
|
+
export function multiplyByRatio<C extends string>(
|
|
669
|
+
money: Money<C>,
|
|
670
|
+
factor: Ratio,
|
|
671
|
+
rounding: RoundingInput,
|
|
672
|
+
scale = money.scale,
|
|
673
|
+
): Money<C> {
|
|
674
|
+
if (typeof rounding === 'function') {
|
|
675
|
+
return roundWithPolicy(money, factor, rounding);
|
|
676
|
+
}
|
|
677
|
+
const minor = money.minor;
|
|
678
|
+
if (
|
|
679
|
+
typeof minor === 'number' &&
|
|
680
|
+
scale === money.scale &&
|
|
681
|
+
factor.n === factor.n &&
|
|
682
|
+
factor.d === factor.d
|
|
683
|
+
) {
|
|
684
|
+
// exact when |product| <= MAX_SAFE_MINOR (both factors are safe integers)
|
|
685
|
+
const product = minor * factor.n;
|
|
686
|
+
if (product <= MAX_SAFE_MINOR && product >= -MAX_SAFE_MINOR) {
|
|
687
|
+
return new Money(money.currency, divideAndRound(product, factor.d, rounding), scale);
|
|
688
|
+
}
|
|
689
|
+
}
|
|
690
|
+
let numerator = toBigInt(minor) * factor.num;
|
|
691
|
+
let denominator = factor.den;
|
|
692
|
+
if (scale > money.scale) {
|
|
693
|
+
numerator *= pow10n(scale - money.scale);
|
|
694
|
+
} else if (scale < money.scale) {
|
|
695
|
+
denominator *= pow10n(money.scale - scale);
|
|
696
|
+
}
|
|
697
|
+
return make(money.currency, divideAndRoundBigint(numerator, denominator, rounding), scale);
|
|
698
|
+
}
|
|
699
|
+
|
|
700
|
+
/** m / divisor, rounded to m's scale (default 'halfExpand'), or with a rounding policy. */
|
|
701
|
+
export function divide<C extends string>(
|
|
702
|
+
money: Money<C>,
|
|
703
|
+
divisor: Factor,
|
|
704
|
+
rounding: RoundingInput = DEFAULT_ROUNDING,
|
|
705
|
+
): Money<C> {
|
|
706
|
+
const divisorRatio = ratio(divisor);
|
|
707
|
+
if (divisorRatio.num === 0n) {
|
|
708
|
+
throw new RangeError('Division by zero');
|
|
709
|
+
}
|
|
710
|
+
|
|
711
|
+
// Fast path: m / (n/d) = m·d / n, rounded once by the same kernel the ratio path uses. Building
|
|
712
|
+
// the inverse ratio d/n would cost bigint arithmetic and a gcd on every call; the divisor's own
|
|
713
|
+
// ratio is cached for small integers and strings. Why it is exact:
|
|
714
|
+
// - makeRatio guarantees d > 0 and n/d in lowest terms, so m·d / n is the same fraction the
|
|
715
|
+
// inverse ratio d/n would give, and only n's sign needs handling;
|
|
716
|
+
// - `x === x` is false only for NaN, which is how a Ratio marks a part that is not a safe
|
|
717
|
+
// integer, so both parts are safe integers here;
|
|
718
|
+
// - m and d are safe integers, so a float product beyond 2^53 - 1 cannot round back down into
|
|
719
|
+
// the safe range: the bound check below rejects every inexact product;
|
|
720
|
+
// - divideAndRound corrects its float quotient exactly (and takes the bigint kernel itself when
|
|
721
|
+
// dividend + divisor exceeds the safe range).
|
|
722
|
+
// A rounding policy (a function, not a mode string) must not take this path: it rounds to its own
|
|
723
|
+
// scale and increment.
|
|
724
|
+
const minor = money.minor;
|
|
725
|
+
const numerator = divisorRatio.n;
|
|
726
|
+
const denominator = divisorRatio.d;
|
|
727
|
+
if (
|
|
728
|
+
typeof minor === 'number' &&
|
|
729
|
+
typeof rounding === 'string' &&
|
|
730
|
+
numerator === numerator &&
|
|
731
|
+
denominator === denominator
|
|
732
|
+
) {
|
|
733
|
+
let dividend = minor * denominator;
|
|
734
|
+
if (dividend <= MAX_SAFE_MINOR && dividend >= -MAX_SAFE_MINOR) {
|
|
735
|
+
// divideAndRound needs a positive divisor: (−p)/(−n) is the same quotient
|
|
736
|
+
let positiveDivisor = numerator;
|
|
737
|
+
if (numerator < 0) {
|
|
738
|
+
dividend = 0 - dividend;
|
|
739
|
+
positiveDivisor = 0 - numerator;
|
|
740
|
+
}
|
|
741
|
+
return new Money(
|
|
742
|
+
money.currency,
|
|
743
|
+
divideAndRound(dividend, positiveDivisor, rounding),
|
|
744
|
+
money.scale,
|
|
745
|
+
);
|
|
746
|
+
}
|
|
747
|
+
}
|
|
748
|
+
|
|
749
|
+
return multiplyByRatio(money, ratio(divisorRatio.den, divisorRatio.num), rounding);
|
|
750
|
+
}
|
|
751
|
+
|
|
752
|
+
/**
|
|
753
|
+
* Rounds to the currency's exponent (or `scale`): `round(money('1.005', 'EUR', {scale: 3}),
|
|
754
|
+
* 'halfEven')`.
|
|
755
|
+
*/
|
|
756
|
+
export function round<C extends string>(
|
|
757
|
+
money: Money<C>,
|
|
758
|
+
rounding: RoundingMode,
|
|
759
|
+
scale?: number,
|
|
760
|
+
): Money<C>;
|
|
761
|
+
/** Rounds to a policy's scale and increment: `round(money('10.03', 'CHF'), cashPolicy('CHF'))`. */
|
|
762
|
+
export function round<C extends string>(money: Money<C>, policy: RoundingPolicy): Money<C>;
|
|
763
|
+
export function round<C extends string>(
|
|
764
|
+
money: Money<C>,
|
|
765
|
+
rounding: RoundingInput,
|
|
766
|
+
scale?: number,
|
|
767
|
+
): Money<C> {
|
|
768
|
+
if (typeof rounding === 'function') {
|
|
769
|
+
return roundWithPolicy(money, ratio(1), rounding);
|
|
770
|
+
}
|
|
771
|
+
return toScale(money, scale ?? currencyExponent(money.currency), rounding);
|
|
772
|
+
}
|
|
773
|
+
|
|
774
|
+
/**
|
|
775
|
+
* Changes the scale; increasing it is always exact, decreasing it rounds (default 'halfExpand').
|
|
776
|
+
*/
|
|
777
|
+
export function toScale<C extends string>(
|
|
778
|
+
money: Money<C>,
|
|
779
|
+
scale: number,
|
|
780
|
+
rounding: RoundingMode = DEFAULT_ROUNDING,
|
|
781
|
+
): Money<C> {
|
|
782
|
+
if (!Number.isInteger(scale) || scale < 0) {
|
|
783
|
+
throw new RangeError(`Invalid scale ${scale}`);
|
|
784
|
+
}
|
|
785
|
+
if (scale === money.scale) {
|
|
786
|
+
return money;
|
|
787
|
+
}
|
|
788
|
+
if (scale > money.scale) {
|
|
789
|
+
return make(money.currency, scaleUp(money.minor, scale - money.scale), scale);
|
|
790
|
+
}
|
|
791
|
+
return make(money.currency, scaleDown(money.minor, money.scale - scale, rounding), scale);
|
|
792
|
+
}
|
|
793
|
+
|
|
794
|
+
// ---------------------------------------------------------------------------------------------
|
|
795
|
+
// Comparison
|
|
796
|
+
// ---------------------------------------------------------------------------------------------
|
|
797
|
+
|
|
798
|
+
/** -1, 0 or 1. Throws on currency mismatch. Works across scales and number/bigint. */
|
|
799
|
+
export function compare<C extends string>(money: Money<C>, other: Money<NoInfer<C>>): -1 | 0 | 1 {
|
|
800
|
+
if (money.currency !== other.currency) {
|
|
801
|
+
mismatch(money, other);
|
|
802
|
+
}
|
|
803
|
+
let left = money.minor;
|
|
804
|
+
let right = other.minor;
|
|
805
|
+
if (money.scale !== other.scale) {
|
|
806
|
+
const scale = Math.max(money.scale, other.scale);
|
|
807
|
+
left = scaleUp(left, scale - money.scale);
|
|
808
|
+
right = scaleUp(right, scale - other.scale);
|
|
809
|
+
}
|
|
810
|
+
// number < bigint comparisons are exact in JS
|
|
811
|
+
if (left < right) {
|
|
812
|
+
return -1;
|
|
813
|
+
}
|
|
814
|
+
return left > right ? 1 : 0;
|
|
815
|
+
}
|
|
816
|
+
|
|
817
|
+
/**
|
|
818
|
+
* Same currency and same value (1.0 EUR at scale 1 equals 1.00 EUR). Different currencies: false.
|
|
819
|
+
*/
|
|
820
|
+
export function equals(money: Money, other: Money): boolean {
|
|
821
|
+
if (money.currency !== other.currency) {
|
|
822
|
+
return false;
|
|
823
|
+
}
|
|
824
|
+
if (money.scale === other.scale) {
|
|
825
|
+
// == compares number and bigint exactly
|
|
826
|
+
return money.minor == other.minor;
|
|
827
|
+
}
|
|
828
|
+
return compare(money, other) === 0;
|
|
829
|
+
}
|
|
830
|
+
|
|
831
|
+
/**
|
|
832
|
+
* Same currency, same value *and* same scale, with number and bigint minor units counted as equal.
|
|
833
|
+
* `equals` treats 1.0 EUR (scale 1) and 1.00 EUR as equal; `identical` does not. For round-trip
|
|
834
|
+
* tests, where the scale must survive too.
|
|
835
|
+
*/
|
|
836
|
+
export function identical(money: Money, other: Money): boolean {
|
|
837
|
+
return (
|
|
838
|
+
money.currency === other.currency && money.scale === other.scale && money.minor == other.minor
|
|
839
|
+
);
|
|
840
|
+
}
|
|
841
|
+
|
|
842
|
+
/** money < other (same currency; any scale). */
|
|
843
|
+
export const lessThan = <C extends string>(money: Money<C>, other: Money<NoInfer<C>>): boolean =>
|
|
844
|
+
compare(money, other) < 0;
|
|
845
|
+
/** money <= other */
|
|
846
|
+
export const lessThanOrEqual = <C extends string>(
|
|
847
|
+
money: Money<C>,
|
|
848
|
+
other: Money<NoInfer<C>>,
|
|
849
|
+
): boolean => compare(money, other) <= 0;
|
|
850
|
+
/** money > other */
|
|
851
|
+
export const greaterThan = <C extends string>(money: Money<C>, other: Money<NoInfer<C>>): boolean =>
|
|
852
|
+
compare(money, other) > 0;
|
|
853
|
+
/** money >= other */
|
|
854
|
+
export const greaterThanOrEqual = <C extends string>(
|
|
855
|
+
money: Money<C>,
|
|
856
|
+
other: Money<NoInfer<C>>,
|
|
857
|
+
): boolean => compare(money, other) >= 0;
|
|
858
|
+
|
|
859
|
+
/** Whether the amount is zero. */
|
|
860
|
+
export const isZero = (money: Money): boolean => money.minor == 0;
|
|
861
|
+
/** Whether the amount is greater than zero. */
|
|
862
|
+
export const isPositive = (money: Money): boolean => money.minor > 0;
|
|
863
|
+
/** Whether the amount is less than zero. */
|
|
864
|
+
export const isNegative = (money: Money): boolean => money.minor < 0;
|
|
865
|
+
/** 1, 0 or -1 for positive, zero and negative amounts. */
|
|
866
|
+
export const sign = (money: Money): -1 | 0 | 1 => {
|
|
867
|
+
if (money.minor > 0) {
|
|
868
|
+
return 1;
|
|
869
|
+
}
|
|
870
|
+
return money.minor < 0 ? -1 : 0;
|
|
871
|
+
};
|
|
872
|
+
|
|
873
|
+
/** The smallest of the amounts (same currency); the first one wins ties. */
|
|
874
|
+
export function min<C extends string>(first: Money<C>, ...rest: Money<NoInfer<C>>[]): Money<C> {
|
|
875
|
+
let smallest = first;
|
|
876
|
+
for (const candidate of rest) {
|
|
877
|
+
if (compare(candidate, smallest) < 0) {
|
|
878
|
+
smallest = candidate;
|
|
879
|
+
}
|
|
880
|
+
}
|
|
881
|
+
return smallest;
|
|
882
|
+
}
|
|
883
|
+
/** The largest of the amounts (same currency); the first one wins ties. */
|
|
884
|
+
export function max<C extends string>(first: Money<C>, ...rest: Money<NoInfer<C>>[]): Money<C> {
|
|
885
|
+
let largest = first;
|
|
886
|
+
for (const candidate of rest) {
|
|
887
|
+
if (compare(candidate, largest) > 0) {
|
|
888
|
+
largest = candidate;
|
|
889
|
+
}
|
|
890
|
+
}
|
|
891
|
+
return largest;
|
|
892
|
+
}
|
|
893
|
+
/** Limits m to [lo, hi]. */
|
|
894
|
+
export function clamp<C extends string>(
|
|
895
|
+
money: Money<C>,
|
|
896
|
+
lo: Money<NoInfer<C>>,
|
|
897
|
+
hi: Money<NoInfer<C>>,
|
|
898
|
+
): Money<C> {
|
|
899
|
+
if (compare(lo, hi) > 0) {
|
|
900
|
+
throw new RangeError('clamp(): lo > hi');
|
|
901
|
+
}
|
|
902
|
+
if (compare(money, lo) < 0) {
|
|
903
|
+
return lo;
|
|
904
|
+
}
|
|
905
|
+
return compare(money, hi) > 0 ? hi : money;
|
|
906
|
+
}
|
|
907
|
+
|
|
908
|
+
// ---------------------------------------------------------------------------------------------
|
|
909
|
+
// Serialisation primitives
|
|
910
|
+
// ---------------------------------------------------------------------------------------------
|
|
911
|
+
|
|
912
|
+
/**
|
|
913
|
+
* Exact decimal string in major units: "12.34", "-0.05", "1000" (JPY). For NUMERIC/DECIMAL columns.
|
|
914
|
+
*/
|
|
915
|
+
export function toDecimal(money: Money): string {
|
|
916
|
+
return formatScaled(money.minor, money.scale);
|
|
917
|
+
}
|
|
918
|
+
|
|
919
|
+
/**
|
|
920
|
+
* The whole major units, truncated toward zero: 12 for 12.34 EUR and -12 for -12.34 EUR. A number
|
|
921
|
+
* while it is a safe integer, a bigint beyond, like `minor`.
|
|
922
|
+
*/
|
|
923
|
+
export function majorPart(money: Money): number | bigint {
|
|
924
|
+
const minor = money.minor;
|
|
925
|
+
if (typeof minor === 'number' && money.scale <= 15) {
|
|
926
|
+
// Taking the remainder out first leaves an exact multiple, so the division is exact. `+ 0`
|
|
927
|
+
// turns -0 into 0.
|
|
928
|
+
const unit = POW10[money.scale]!;
|
|
929
|
+
return (minor - (minor % unit)) / unit + 0;
|
|
930
|
+
}
|
|
931
|
+
// bigint division truncates toward zero, like the fast path
|
|
932
|
+
return normalizeMinor(toBigInt(minor) / pow10n(money.scale));
|
|
933
|
+
}
|
|
934
|
+
|
|
935
|
+
/**
|
|
936
|
+
* What is left after `majorPart`, in 10^-scale units and with the amount's sign: 34 for 12.34
|
|
937
|
+
* EUR, -34 for -12.34 EUR, 5 for 1.005 EUR at scale 3.
|
|
938
|
+
*/
|
|
939
|
+
export function minorPart(money: Money): number | bigint {
|
|
940
|
+
const minor = money.minor;
|
|
941
|
+
if (typeof minor === 'number' && money.scale <= 15) {
|
|
942
|
+
// % on safe integers is exact and keeps the dividend's sign; `+ 0` turns -0 into 0.
|
|
943
|
+
return (minor % POW10[money.scale]!) + 0;
|
|
944
|
+
}
|
|
945
|
+
return normalizeMinor(toBigInt(minor) % pow10n(money.scale));
|
|
946
|
+
}
|
|
947
|
+
|
|
948
|
+
/** Minor units as a bigint (always safe; use for BIGINT columns). */
|
|
949
|
+
export function toMinor(money: Money): bigint {
|
|
950
|
+
return toBigInt(money.minor);
|
|
951
|
+
}
|
|
952
|
+
|
|
953
|
+
/** Minor units as a number; throws if not a safe integer. */
|
|
954
|
+
export function toMinorNumber(money: Money): number {
|
|
955
|
+
if (typeof money.minor === 'bigint') {
|
|
956
|
+
throw new RangeError(`${money} does not fit in a safe integer; use toMinor()`);
|
|
957
|
+
}
|
|
958
|
+
return money.minor;
|
|
959
|
+
}
|
|
960
|
+
|
|
961
|
+
/** Parses `{ amount: "12.34", currency: "EUR" }` (as produced by JSON.stringify(money)). */
|
|
962
|
+
export function fromJSON<C extends CurrencyInput = CurrencyInput>(
|
|
963
|
+
json: MoneyJSON<C> | string,
|
|
964
|
+
options?: MoneyOptions,
|
|
965
|
+
): Money<C> {
|
|
966
|
+
const parsed = typeof json === 'string' ? (JSON.parse(json) as MoneyJSON<C>) : json;
|
|
967
|
+
if (
|
|
968
|
+
parsed === null ||
|
|
969
|
+
typeof parsed !== 'object' ||
|
|
970
|
+
typeof parsed.amount !== 'string' ||
|
|
971
|
+
typeof parsed.currency !== 'string'
|
|
972
|
+
) {
|
|
973
|
+
throw new TypeError('Expected { amount: string, currency: string }');
|
|
974
|
+
}
|
|
975
|
+
return money(parsed.amount, parsed.currency, options);
|
|
976
|
+
}
|
|
977
|
+
|
|
978
|
+
export type { Factor, Ratio } from './decimal.js';
|
|
979
|
+
export { ratio } from './decimal.js';
|