@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/money.ts
ADDED
|
@@ -0,0 +1,781 @@
|
|
|
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
|
+
/** Thrown when two amounts in different currencies are combined. */
|
|
36
|
+
export class CurrencyMismatchError extends TypeError {
|
|
37
|
+
override name = 'CurrencyMismatchError';
|
|
38
|
+
declare readonly expected: string;
|
|
39
|
+
declare readonly actual: string;
|
|
40
|
+
constructor(expected: string, actual: string) {
|
|
41
|
+
super(`Currency mismatch: ${expected} vs ${actual}`);
|
|
42
|
+
this.expected = expected;
|
|
43
|
+
this.actual = actual;
|
|
44
|
+
}
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
/**
|
|
48
|
+
* An immutable amount of money: an integer number of 10^-scale units of `currency`.
|
|
49
|
+
*
|
|
50
|
+
* `minor` is a JS number whenever it is a safe integer (|v| <= 2^53 - 1) and a bigint otherwise, so
|
|
51
|
+
* ordinary amounts never allocate a bigint, and huge or high-precision amounts never lose a digit.
|
|
52
|
+
* `scale` is normally the currency's ISO exponent (2 for EUR) but can be larger for sub-minor
|
|
53
|
+
* precision (unit prices, FX intermediates); `round()` brings it back.
|
|
54
|
+
*
|
|
55
|
+
* Instances are not frozen (Object.freeze costs 5-8x on construction in V8 and JSC; see bench/),
|
|
56
|
+
* but every field is readonly and no operation mutates. Create values with `money()` /
|
|
57
|
+
* `fromMinor()`.
|
|
58
|
+
*
|
|
59
|
+
* The class carries the core methods only. Opt-in modules (`@ducatjs/money/allocate`,
|
|
60
|
+
* `@ducatjs/money/tax`, `@ducatjs/money/format`, ...) add theirs when imported; see `extendMoney`.
|
|
61
|
+
*/
|
|
62
|
+
class Money<C extends string = string> {
|
|
63
|
+
declare readonly currency: C;
|
|
64
|
+
declare readonly minor: number | bigint;
|
|
65
|
+
declare readonly scale: number;
|
|
66
|
+
/** @internal */
|
|
67
|
+
constructor(currency: C, minor: number | bigint, scale: number) {
|
|
68
|
+
this.currency = currency;
|
|
69
|
+
this.minor = minor;
|
|
70
|
+
this.scale = scale;
|
|
71
|
+
}
|
|
72
|
+
/** "12.34 EUR" */
|
|
73
|
+
toString(): string {
|
|
74
|
+
return `${formatScaled(this.minor, this.scale)} ${this.currency}`;
|
|
75
|
+
}
|
|
76
|
+
toJSON(): MoneyJSON<C> {
|
|
77
|
+
return { amount: formatScaled(this.minor, this.scale), currency: this.currency };
|
|
78
|
+
}
|
|
79
|
+
/** Blocks `a + b`, `a > b`, `+a`: arithmetic and comparison must go through the library. */
|
|
80
|
+
[Symbol.toPrimitive](hint: string): string {
|
|
81
|
+
if (hint === 'string') {
|
|
82
|
+
return this.toString();
|
|
83
|
+
}
|
|
84
|
+
throw new TypeError(
|
|
85
|
+
'Money cannot be converted to a number; use add(), compare(), toDecimal() etc.',
|
|
86
|
+
);
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
// Methods. Each one is a thin wrapper over the free function of the same name (also exported), so
|
|
90
|
+
// `a.add(b)` and `add(a, b)` are the same code. Operands are Money only: a bare number is never
|
|
91
|
+
// guessed to mean major or minor units.
|
|
92
|
+
|
|
93
|
+
// arithmetic
|
|
94
|
+
/** this + other (same currency; any scale) */
|
|
95
|
+
add(other: Money<C>): Money<C> {
|
|
96
|
+
return add(this, other);
|
|
97
|
+
}
|
|
98
|
+
/** this - other */
|
|
99
|
+
subtract(other: Money<C>): Money<C> {
|
|
100
|
+
return subtract(this, other);
|
|
101
|
+
}
|
|
102
|
+
/**
|
|
103
|
+
* this * factor, rounded to this scale. `factor` is exact: integer, decimal string ('1.075'),
|
|
104
|
+
* bigint or ratio().
|
|
105
|
+
*/
|
|
106
|
+
multiply(factor: Factor, rounding?: RoundingMode): Money<C> {
|
|
107
|
+
return multiply(this, factor, rounding);
|
|
108
|
+
}
|
|
109
|
+
/** this / divisor, rounded to this scale */
|
|
110
|
+
divide(divisor: Factor, rounding?: RoundingMode): Money<C> {
|
|
111
|
+
return divide(this, divisor, rounding);
|
|
112
|
+
}
|
|
113
|
+
negate(): Money<C> {
|
|
114
|
+
return negate(this);
|
|
115
|
+
}
|
|
116
|
+
abs(): Money<C> {
|
|
117
|
+
return abs(this);
|
|
118
|
+
}
|
|
119
|
+
/** Rounds to the currency's exponent (or `scale`). */
|
|
120
|
+
round(rounding: RoundingMode, scale?: number): Money<C> {
|
|
121
|
+
return round(this, rounding, scale);
|
|
122
|
+
}
|
|
123
|
+
/** Changes the scale; decreasing it rounds (default 'halfExpand'). */
|
|
124
|
+
toScale(scale: number, rounding?: RoundingMode): Money<C> {
|
|
125
|
+
return toScale(this, scale, rounding);
|
|
126
|
+
}
|
|
127
|
+
// comparison
|
|
128
|
+
/** -1, 0 or 1; throws on currency mismatch */
|
|
129
|
+
compare(other: Money<C>): -1 | 0 | 1 {
|
|
130
|
+
return compare(this, other);
|
|
131
|
+
}
|
|
132
|
+
/** same currency and value; a different currency is simply not equal */
|
|
133
|
+
equals(other: Money): boolean {
|
|
134
|
+
return equals(this, other);
|
|
135
|
+
}
|
|
136
|
+
lessThan(other: Money<C>): boolean {
|
|
137
|
+
return compare(this, other) < 0;
|
|
138
|
+
}
|
|
139
|
+
lessThanOrEqual(other: Money<C>): boolean {
|
|
140
|
+
return compare(this, other) <= 0;
|
|
141
|
+
}
|
|
142
|
+
greaterThan(other: Money<C>): boolean {
|
|
143
|
+
return compare(this, other) > 0;
|
|
144
|
+
}
|
|
145
|
+
greaterThanOrEqual(other: Money<C>): boolean {
|
|
146
|
+
return compare(this, other) >= 0;
|
|
147
|
+
}
|
|
148
|
+
isZero(): boolean {
|
|
149
|
+
return this.minor == 0;
|
|
150
|
+
}
|
|
151
|
+
isPositive(): boolean {
|
|
152
|
+
return this.minor > 0;
|
|
153
|
+
}
|
|
154
|
+
isNegative(): boolean {
|
|
155
|
+
return this.minor < 0;
|
|
156
|
+
}
|
|
157
|
+
sign(): -1 | 0 | 1 {
|
|
158
|
+
return sign(this);
|
|
159
|
+
}
|
|
160
|
+
min(...others: Money<C>[]): Money<C> {
|
|
161
|
+
return min(this, ...others);
|
|
162
|
+
}
|
|
163
|
+
max(...others: Money<C>[]): Money<C> {
|
|
164
|
+
return max(this, ...others);
|
|
165
|
+
}
|
|
166
|
+
clamp(lo: Money<C>, hi: Money<C>): Money<C> {
|
|
167
|
+
return clamp(this, lo, hi);
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
// output
|
|
171
|
+
/** Exact decimal string in major units: "12.34" */
|
|
172
|
+
toDecimal(): string {
|
|
173
|
+
return formatScaled(this.minor, this.scale);
|
|
174
|
+
}
|
|
175
|
+
/** Minor units as a bigint (BIGINT columns) */
|
|
176
|
+
toMinor(): bigint {
|
|
177
|
+
return toBigInt(this.minor);
|
|
178
|
+
}
|
|
179
|
+
/** Minor units as a number; throws beyond 2^53 */
|
|
180
|
+
toMinorNumber(): number {
|
|
181
|
+
return toMinorNumber(this);
|
|
182
|
+
}
|
|
183
|
+
}
|
|
184
|
+
export type { Money };
|
|
185
|
+
|
|
186
|
+
/** Whether a value is a Money from this package. */
|
|
187
|
+
export function isMoney(value: unknown): value is Money {
|
|
188
|
+
return value instanceof Money;
|
|
189
|
+
}
|
|
190
|
+
|
|
191
|
+
/**
|
|
192
|
+
* Which module installed each added method, so a second copy of the same module can replace its
|
|
193
|
+
* own.
|
|
194
|
+
*/
|
|
195
|
+
const methodOwners = new Map<string, string>();
|
|
196
|
+
|
|
197
|
+
/**
|
|
198
|
+
* Names `extendMoney` refuses: the ones every object inherits, whose meaning other code relies on.
|
|
199
|
+
* `toLocaleString` is allowed, since a formatting module may want to provide it.
|
|
200
|
+
*/
|
|
201
|
+
const RESERVED_NAMES = new Set(
|
|
202
|
+
Object.getOwnPropertyNames(Object.prototype).filter((name) => name !== 'toLocaleString'),
|
|
203
|
+
);
|
|
204
|
+
|
|
205
|
+
/** Options for `extendMoney`. */
|
|
206
|
+
export interface ExtendMoneyOptions {
|
|
207
|
+
/**
|
|
208
|
+
* Who is installing the methods, e.g. '@ducatjs/money/allocate'. Installing again under the same
|
|
209
|
+
* owner replaces that owner's methods, which happens when a module is loaded twice (hot reload,
|
|
210
|
+
* two copies of the package). Without an owner, or under a different one, an existing name
|
|
211
|
+
* throws.
|
|
212
|
+
*/
|
|
213
|
+
readonly owner?: string;
|
|
214
|
+
}
|
|
215
|
+
|
|
216
|
+
/**
|
|
217
|
+
* Adds methods to every Money (this is how `@ducatjs/money/allocate`, `@ducatjs/money/format`, ...
|
|
218
|
+
* install theirs). Declare their types with `declare module '@ducatjs/money' { interface Money<C
|
|
219
|
+
* extends string> { ... } }`. The methods are non-enumerable, like class methods. A name that Money
|
|
220
|
+
* already has (one of its own methods, or one added by a different owner) throws, so two modules
|
|
221
|
+
* cannot silently fight over it.
|
|
222
|
+
*/
|
|
223
|
+
export function extendMoney(
|
|
224
|
+
methods: Record<string, (this: Money, ...args: never[]) => unknown>,
|
|
225
|
+
options?: ExtendMoneyOptions,
|
|
226
|
+
): void {
|
|
227
|
+
const prototype = Money.prototype as unknown as Record<string, unknown>;
|
|
228
|
+
const owner = options?.owner;
|
|
229
|
+
|
|
230
|
+
for (const name of Object.keys(methods)) {
|
|
231
|
+
const method = methods[name];
|
|
232
|
+
|
|
233
|
+
if (RESERVED_NAMES.has(name)) {
|
|
234
|
+
throw new TypeError(`Money#${name} is reserved`);
|
|
235
|
+
}
|
|
236
|
+
|
|
237
|
+
// Replacing an existing method would silently change behaviour for every caller, unless it is
|
|
238
|
+
// the same function or the same owner installing its own methods again.
|
|
239
|
+
const previousOwner = methodOwners.get(name);
|
|
240
|
+
const isOwnReinstall = owner !== undefined && previousOwner === owner;
|
|
241
|
+
if (Object.hasOwn(prototype, name) && prototype[name] !== method && !isOwnReinstall) {
|
|
242
|
+
throw new TypeError(`Money#${name} is already defined`);
|
|
243
|
+
}
|
|
244
|
+
|
|
245
|
+
// Non-enumerable, like the class's own methods, so Object.keys and spreads see only the fields.
|
|
246
|
+
Object.defineProperty(prototype, name, {
|
|
247
|
+
value: method,
|
|
248
|
+
writable: true,
|
|
249
|
+
configurable: true,
|
|
250
|
+
enumerable: false,
|
|
251
|
+
});
|
|
252
|
+
if (owner !== undefined) {
|
|
253
|
+
methodOwners.set(name, owner);
|
|
254
|
+
}
|
|
255
|
+
}
|
|
256
|
+
}
|
|
257
|
+
|
|
258
|
+
/** @internal construct from a value that may be an unsafe bigint */
|
|
259
|
+
export function make<C extends string>(
|
|
260
|
+
currency: C,
|
|
261
|
+
minor: number | bigint,
|
|
262
|
+
scale: number,
|
|
263
|
+
): Money<C> {
|
|
264
|
+
return new Money(currency, typeof minor === 'bigint' ? normalizeMinor(minor) : minor, scale);
|
|
265
|
+
}
|
|
266
|
+
|
|
267
|
+
const toBigInt = (minor: number | bigint) => (typeof minor === 'bigint' ? minor : BigInt(minor));
|
|
268
|
+
|
|
269
|
+
/** v * 10^e exactly (e >= 0) */
|
|
270
|
+
export function scaleUp(minor: number | bigint, exponent: number): number | bigint {
|
|
271
|
+
if (exponent === 0) {
|
|
272
|
+
return minor;
|
|
273
|
+
}
|
|
274
|
+
if (typeof minor === 'number' && exponent <= 15) {
|
|
275
|
+
const scaled = minor * POW10[exponent]!;
|
|
276
|
+
if (scaled <= MAX_SAFE_MINOR && scaled >= -MAX_SAFE_MINOR) {
|
|
277
|
+
return scaled;
|
|
278
|
+
}
|
|
279
|
+
}
|
|
280
|
+
return normalizeMinor(toBigInt(minor) * pow10n(exponent));
|
|
281
|
+
}
|
|
282
|
+
|
|
283
|
+
/** v / 10^e rounded (e >= 0) */
|
|
284
|
+
export function scaleDown(
|
|
285
|
+
minor: number | bigint,
|
|
286
|
+
exponent: number,
|
|
287
|
+
mode: RoundingMode,
|
|
288
|
+
): number | bigint {
|
|
289
|
+
if (exponent === 0) {
|
|
290
|
+
return minor;
|
|
291
|
+
}
|
|
292
|
+
if (typeof minor === 'number' && exponent <= 15) {
|
|
293
|
+
return divideAndRound(minor, POW10[exponent]!, mode);
|
|
294
|
+
}
|
|
295
|
+
return normalizeMinor(divideAndRoundBigint(toBigInt(minor), pow10n(exponent), mode));
|
|
296
|
+
}
|
|
297
|
+
|
|
298
|
+
// ---------------------------------------------------------------------------------------------
|
|
299
|
+
// Construction
|
|
300
|
+
// ---------------------------------------------------------------------------------------------
|
|
301
|
+
|
|
302
|
+
/** Options for `money()` and `fromJSON()`: the scale to keep and how to round extra decimals. */
|
|
303
|
+
export interface MoneyOptions {
|
|
304
|
+
/** Decimal places to keep (default: the currency's exponent). */
|
|
305
|
+
readonly scale?: number;
|
|
306
|
+
/** How to round input with more decimals than `scale` (default 'unnecessary': throw). */
|
|
307
|
+
readonly rounding?: RoundingMode;
|
|
308
|
+
}
|
|
309
|
+
|
|
310
|
+
/**
|
|
311
|
+
* Creates money from an amount in major units.
|
|
312
|
+
*
|
|
313
|
+
* money('12.34', 'EUR') // exact decimal string: the recommended form
|
|
314
|
+
* money(12, 'EUR') // integers are major units: 12.00 EUR
|
|
315
|
+
* money(12.34, 'EUR') // non-integer numbers are read at their shortest decimal form ("12.34")
|
|
316
|
+
* money(10n ** 30n, 'USD')
|
|
317
|
+
*
|
|
318
|
+
* Throws if the amount has more decimals than the currency (or `scale`) unless `rounding` is given,
|
|
319
|
+
* so `money(0.1 + 0.2, 'EUR')` throws rather than silently becoming 0.30.
|
|
320
|
+
*/
|
|
321
|
+
export function money<C extends CurrencyInput>(
|
|
322
|
+
amount: string | number | bigint,
|
|
323
|
+
currency: C,
|
|
324
|
+
options?: MoneyOptions,
|
|
325
|
+
): Money<C> {
|
|
326
|
+
const scale = options?.scale ?? currencyExponent(currency);
|
|
327
|
+
if (typeof amount === 'string') {
|
|
328
|
+
const parsed = parsePlainDecimal(amount) ?? parseDecimal(amount);
|
|
329
|
+
return fromScaled(
|
|
330
|
+
currency,
|
|
331
|
+
parsed.digits,
|
|
332
|
+
parsed.scale,
|
|
333
|
+
scale,
|
|
334
|
+
options?.rounding ?? 'unnecessary',
|
|
335
|
+
amount,
|
|
336
|
+
);
|
|
337
|
+
}
|
|
338
|
+
if (typeof amount === 'number') {
|
|
339
|
+
if (Number.isSafeInteger(amount)) {
|
|
340
|
+
return make(currency, scaleUp(amount, scale), scale);
|
|
341
|
+
}
|
|
342
|
+
if (!Number.isFinite(amount)) {
|
|
343
|
+
throw new RangeError(`Invalid amount ${amount}`);
|
|
344
|
+
}
|
|
345
|
+
const parsed = parseDecimal(String(amount));
|
|
346
|
+
return fromScaled(
|
|
347
|
+
currency,
|
|
348
|
+
parsed.digits,
|
|
349
|
+
parsed.scale,
|
|
350
|
+
scale,
|
|
351
|
+
options?.rounding ?? 'unnecessary',
|
|
352
|
+
amount,
|
|
353
|
+
);
|
|
354
|
+
}
|
|
355
|
+
if (typeof amount === 'bigint') {
|
|
356
|
+
return make(currency, scaleUp(normalizeMinor(amount), scale), scale);
|
|
357
|
+
}
|
|
358
|
+
throw new TypeError(`Invalid amount ${String(amount)}`);
|
|
359
|
+
}
|
|
360
|
+
|
|
361
|
+
function fromScaled<C extends string>(
|
|
362
|
+
currency: C,
|
|
363
|
+
digits: number | bigint,
|
|
364
|
+
from: number,
|
|
365
|
+
to: number,
|
|
366
|
+
mode: RoundingMode,
|
|
367
|
+
input: unknown,
|
|
368
|
+
): Money<C> {
|
|
369
|
+
if (typeof digits === 'bigint') {
|
|
370
|
+
digits = normalizeMinor(digits);
|
|
371
|
+
}
|
|
372
|
+
if (from === to) {
|
|
373
|
+
return new Money(currency, digits, to);
|
|
374
|
+
}
|
|
375
|
+
if (from < to) {
|
|
376
|
+
return make(currency, scaleUp(digits, to - from), to);
|
|
377
|
+
}
|
|
378
|
+
try {
|
|
379
|
+
return make(currency, scaleDown(digits, from - to, mode), to);
|
|
380
|
+
} catch (error) {
|
|
381
|
+
if (error instanceof RoundingError) {
|
|
382
|
+
throw new RoundingError(
|
|
383
|
+
`${String(input)} has more than ${to} decimal places for ${currency}; pass { rounding } or { scale }`,
|
|
384
|
+
);
|
|
385
|
+
}
|
|
386
|
+
throw error;
|
|
387
|
+
}
|
|
388
|
+
}
|
|
389
|
+
|
|
390
|
+
/**
|
|
391
|
+
* Creates money from an integer count of minor units (cents): `fromMinor(1234, 'EUR')` is 12.34
|
|
392
|
+
* EUR. This is the form to read from a BIGINT column or a payment processor (but see
|
|
393
|
+
* `stripe`/`adyen` for processors whose exponent differs from ISO).
|
|
394
|
+
*/
|
|
395
|
+
export function fromMinor<C extends CurrencyInput>(
|
|
396
|
+
minor: number | bigint,
|
|
397
|
+
currency: C,
|
|
398
|
+
scale?: number,
|
|
399
|
+
): Money<C> {
|
|
400
|
+
const resolvedScale = scale ?? currencyExponent(currency);
|
|
401
|
+
if (typeof minor === 'number') {
|
|
402
|
+
if (!Number.isSafeInteger(minor)) {
|
|
403
|
+
throw new RangeError(`Minor units must be a safe integer, got ${minor}; pass a bigint`);
|
|
404
|
+
}
|
|
405
|
+
return new Money(currency, minor + 0, resolvedScale);
|
|
406
|
+
}
|
|
407
|
+
if (typeof minor !== 'bigint') {
|
|
408
|
+
throw new TypeError(`Invalid minor units ${String(minor)}`);
|
|
409
|
+
}
|
|
410
|
+
return make(currency, minor, resolvedScale);
|
|
411
|
+
}
|
|
412
|
+
|
|
413
|
+
/** Zero in a currency, at its exponent (or `scale`). */
|
|
414
|
+
export function zero<C extends CurrencyInput>(currency: C, scale?: number): Money<C> {
|
|
415
|
+
return new Money(currency, 0, scale ?? currencyExponent(currency));
|
|
416
|
+
}
|
|
417
|
+
|
|
418
|
+
// ---------------------------------------------------------------------------------------------
|
|
419
|
+
// Arithmetic
|
|
420
|
+
// ---------------------------------------------------------------------------------------------
|
|
421
|
+
|
|
422
|
+
function mismatch(money: Money, other: Money): never {
|
|
423
|
+
throw new CurrencyMismatchError(money.currency, other.currency);
|
|
424
|
+
}
|
|
425
|
+
|
|
426
|
+
function addUsingBigInt<C extends string>(money: Money<C>, other: Money, sign: 1 | -1): Money<C> {
|
|
427
|
+
const scale = Math.max(money.scale, other.scale);
|
|
428
|
+
const left = toBigInt(scaleUp(money.minor, scale - money.scale));
|
|
429
|
+
const right = toBigInt(scaleUp(other.minor, scale - other.scale));
|
|
430
|
+
return make(money.currency, sign === 1 ? left + right : left - right, scale);
|
|
431
|
+
}
|
|
432
|
+
|
|
433
|
+
/**
|
|
434
|
+
* a + b. Mixing currencies is a type error for literal currency types and a runtime error
|
|
435
|
+
* otherwise.
|
|
436
|
+
*/
|
|
437
|
+
export function add<C extends string>(money: Money<C>, other: Money<NoInfer<C>>): Money<C> {
|
|
438
|
+
if (money.currency !== other.currency) {
|
|
439
|
+
mismatch(money, other);
|
|
440
|
+
}
|
|
441
|
+
const left = money.minor;
|
|
442
|
+
const right = other.minor;
|
|
443
|
+
if (typeof left === 'number' && typeof right === 'number' && money.scale === other.scale) {
|
|
444
|
+
// exact whenever |sum| <= MAX_SAFE_MINOR: both inputs are safe integers
|
|
445
|
+
const sum = left + right;
|
|
446
|
+
if (sum <= MAX_SAFE_MINOR && sum >= -MAX_SAFE_MINOR) {
|
|
447
|
+
return new Money(money.currency, sum, money.scale);
|
|
448
|
+
}
|
|
449
|
+
}
|
|
450
|
+
return addUsingBigInt(money, other, 1);
|
|
451
|
+
}
|
|
452
|
+
|
|
453
|
+
/** a - b */
|
|
454
|
+
export function subtract<C extends string>(money: Money<C>, other: Money<NoInfer<C>>): Money<C> {
|
|
455
|
+
if (money.currency !== other.currency) {
|
|
456
|
+
mismatch(money, other);
|
|
457
|
+
}
|
|
458
|
+
const left = money.minor;
|
|
459
|
+
const right = other.minor;
|
|
460
|
+
if (typeof left === 'number' && typeof right === 'number' && money.scale === other.scale) {
|
|
461
|
+
const difference = left - right;
|
|
462
|
+
if (difference <= MAX_SAFE_MINOR && difference >= -MAX_SAFE_MINOR) {
|
|
463
|
+
return new Money(money.currency, difference + 0, money.scale);
|
|
464
|
+
}
|
|
465
|
+
}
|
|
466
|
+
return addUsingBigInt(money, other, -1);
|
|
467
|
+
}
|
|
468
|
+
|
|
469
|
+
type IsUnion<T, U = T> = T extends unknown ? ([U] extends [T] ? false : true) : never;
|
|
470
|
+
/**
|
|
471
|
+
* Rejects arrays whose element type mixes several literal currencies, e.g. (Money<'EUR'> |
|
|
472
|
+
* Money<'USD'>)[].
|
|
473
|
+
*/
|
|
474
|
+
type SingleCurrency<C extends string> =
|
|
475
|
+
true extends IsUnion<C> ? { readonly 'mixed currencies are not allowed': C } : unknown;
|
|
476
|
+
|
|
477
|
+
/** Sum of a list (same currency; any scale). An empty list needs `currency` and returns zero. */
|
|
478
|
+
export function sum<C extends string>(
|
|
479
|
+
items: readonly Money<C>[] & SingleCurrency<C>,
|
|
480
|
+
currency?: NoInfer<C>,
|
|
481
|
+
): Money<C> {
|
|
482
|
+
const count = items.length;
|
|
483
|
+
if (count === 0) {
|
|
484
|
+
if (currency === undefined) {
|
|
485
|
+
throw new RangeError('sum() of an empty list needs a currency');
|
|
486
|
+
}
|
|
487
|
+
return zero(currency);
|
|
488
|
+
}
|
|
489
|
+
|
|
490
|
+
let total = items[0]!;
|
|
491
|
+
if (currency !== undefined && total.currency !== currency) {
|
|
492
|
+
throw new CurrencyMismatchError(currency, total.currency);
|
|
493
|
+
}
|
|
494
|
+
const itemCurrency = total.currency;
|
|
495
|
+
const scale = total.scale;
|
|
496
|
+
|
|
497
|
+
// Fast loop on plain numbers: each partial sum of safe integers is exact while it stays within
|
|
498
|
+
// MAX_SAFE_MINOR. It falls back to add() at the first bigint, scale change or overflow. NaN marks
|
|
499
|
+
// "no fast total".
|
|
500
|
+
let fastTotal = typeof total.minor === 'number' ? total.minor : NaN;
|
|
501
|
+
let i = 1;
|
|
502
|
+
for (; i < count && fastTotal === fastTotal; i++) {
|
|
503
|
+
const item = items[i]!;
|
|
504
|
+
if (item.currency !== itemCurrency) {
|
|
505
|
+
mismatch(total, item);
|
|
506
|
+
}
|
|
507
|
+
if (typeof item.minor !== 'number' || item.scale !== scale) {
|
|
508
|
+
break;
|
|
509
|
+
}
|
|
510
|
+
const next = fastTotal + item.minor;
|
|
511
|
+
if (!(next <= MAX_SAFE_MINOR && next >= -MAX_SAFE_MINOR)) {
|
|
512
|
+
break;
|
|
513
|
+
}
|
|
514
|
+
fastTotal = next;
|
|
515
|
+
}
|
|
516
|
+
if (fastTotal === fastTotal) {
|
|
517
|
+
total = new Money(itemCurrency, fastTotal, scale);
|
|
518
|
+
}
|
|
519
|
+
|
|
520
|
+
for (; i < count; i++) {
|
|
521
|
+
total = add(total, items[i]!);
|
|
522
|
+
}
|
|
523
|
+
return total;
|
|
524
|
+
}
|
|
525
|
+
|
|
526
|
+
/** -money */
|
|
527
|
+
export function negate<C extends string>(money: Money<C>): Money<C> {
|
|
528
|
+
const minor = money.minor;
|
|
529
|
+
return new Money(
|
|
530
|
+
money.currency,
|
|
531
|
+
typeof minor === 'number' ? 0 - minor : normalizeMinor(-minor),
|
|
532
|
+
money.scale,
|
|
533
|
+
);
|
|
534
|
+
}
|
|
535
|
+
|
|
536
|
+
/** |money| */
|
|
537
|
+
export function abs<C extends string>(money: Money<C>): Money<C> {
|
|
538
|
+
return money.minor < 0 ? negate(money) : money;
|
|
539
|
+
}
|
|
540
|
+
|
|
541
|
+
/**
|
|
542
|
+
* m * factor, rounded to m's scale. `factor` is exact: an integer, a decimal string ('1.075'), a
|
|
543
|
+
* bigint, or a `ratio()`. Rounding defaults to 'halfExpand' (ties away from zero); pass
|
|
544
|
+
* 'unnecessary' to throw instead.
|
|
545
|
+
*/
|
|
546
|
+
export function multiply<C extends string>(
|
|
547
|
+
money: Money<C>,
|
|
548
|
+
factor: Factor,
|
|
549
|
+
rounding: RoundingMode = DEFAULT_ROUNDING,
|
|
550
|
+
): Money<C> {
|
|
551
|
+
const minor = money.minor;
|
|
552
|
+
if (typeof factor === 'number' && Number.isSafeInteger(factor) && typeof minor === 'number') {
|
|
553
|
+
const product = minor * factor;
|
|
554
|
+
if (product <= MAX_SAFE_MINOR && product >= -MAX_SAFE_MINOR) {
|
|
555
|
+
return new Money(money.currency, product + 0, money.scale);
|
|
556
|
+
}
|
|
557
|
+
}
|
|
558
|
+
return multiplyByRatio(money, ratio(factor), rounding);
|
|
559
|
+
}
|
|
560
|
+
|
|
561
|
+
/** @internal m * r, rounded */
|
|
562
|
+
export function multiplyByRatio<C extends string>(
|
|
563
|
+
money: Money<C>,
|
|
564
|
+
factor: Ratio,
|
|
565
|
+
rounding: RoundingMode,
|
|
566
|
+
scale = money.scale,
|
|
567
|
+
): Money<C> {
|
|
568
|
+
const minor = money.minor;
|
|
569
|
+
if (
|
|
570
|
+
typeof minor === 'number' &&
|
|
571
|
+
scale === money.scale &&
|
|
572
|
+
factor.n === factor.n &&
|
|
573
|
+
factor.d === factor.d
|
|
574
|
+
) {
|
|
575
|
+
// exact when |product| <= MAX_SAFE_MINOR (both factors are safe integers)
|
|
576
|
+
const product = minor * factor.n;
|
|
577
|
+
if (product <= MAX_SAFE_MINOR && product >= -MAX_SAFE_MINOR) {
|
|
578
|
+
return new Money(money.currency, divideAndRound(product, factor.d, rounding), scale);
|
|
579
|
+
}
|
|
580
|
+
}
|
|
581
|
+
let numerator = toBigInt(minor) * factor.num;
|
|
582
|
+
let denominator = factor.den;
|
|
583
|
+
if (scale > money.scale) {
|
|
584
|
+
numerator *= pow10n(scale - money.scale);
|
|
585
|
+
} else if (scale < money.scale) {
|
|
586
|
+
denominator *= pow10n(money.scale - scale);
|
|
587
|
+
}
|
|
588
|
+
return make(money.currency, divideAndRoundBigint(numerator, denominator, rounding), scale);
|
|
589
|
+
}
|
|
590
|
+
|
|
591
|
+
/** m / divisor, rounded to m's scale (default 'halfExpand'). */
|
|
592
|
+
export function divide<C extends string>(
|
|
593
|
+
money: Money<C>,
|
|
594
|
+
divisor: Factor,
|
|
595
|
+
rounding: RoundingMode = DEFAULT_ROUNDING,
|
|
596
|
+
): Money<C> {
|
|
597
|
+
const divisorRatio = ratio(divisor);
|
|
598
|
+
if (divisorRatio.num === 0n) {
|
|
599
|
+
throw new RangeError('Division by zero');
|
|
600
|
+
}
|
|
601
|
+
return multiplyByRatio(money, ratio(divisorRatio.den, divisorRatio.num), rounding);
|
|
602
|
+
}
|
|
603
|
+
|
|
604
|
+
/**
|
|
605
|
+
* Rounds to the currency's exponent (or `scale`): `round(money('1.005', 'EUR', {scale: 3}),
|
|
606
|
+
* 'halfEven')`.
|
|
607
|
+
*/
|
|
608
|
+
export function round<C extends string>(
|
|
609
|
+
money: Money<C>,
|
|
610
|
+
rounding: RoundingMode,
|
|
611
|
+
scale?: number,
|
|
612
|
+
): Money<C> {
|
|
613
|
+
return toScale(money, scale ?? currencyExponent(money.currency), rounding);
|
|
614
|
+
}
|
|
615
|
+
|
|
616
|
+
/**
|
|
617
|
+
* Changes the scale; increasing it is always exact, decreasing it rounds (default 'halfExpand').
|
|
618
|
+
*/
|
|
619
|
+
export function toScale<C extends string>(
|
|
620
|
+
money: Money<C>,
|
|
621
|
+
scale: number,
|
|
622
|
+
rounding: RoundingMode = DEFAULT_ROUNDING,
|
|
623
|
+
): Money<C> {
|
|
624
|
+
if (!Number.isInteger(scale) || scale < 0) {
|
|
625
|
+
throw new RangeError(`Invalid scale ${scale}`);
|
|
626
|
+
}
|
|
627
|
+
if (scale === money.scale) {
|
|
628
|
+
return money;
|
|
629
|
+
}
|
|
630
|
+
if (scale > money.scale) {
|
|
631
|
+
return make(money.currency, scaleUp(money.minor, scale - money.scale), scale);
|
|
632
|
+
}
|
|
633
|
+
return make(money.currency, scaleDown(money.minor, money.scale - scale, rounding), scale);
|
|
634
|
+
}
|
|
635
|
+
|
|
636
|
+
// ---------------------------------------------------------------------------------------------
|
|
637
|
+
// Comparison
|
|
638
|
+
// ---------------------------------------------------------------------------------------------
|
|
639
|
+
|
|
640
|
+
/** -1, 0 or 1. Throws on currency mismatch. Works across scales and number/bigint. */
|
|
641
|
+
export function compare<C extends string>(money: Money<C>, other: Money<NoInfer<C>>): -1 | 0 | 1 {
|
|
642
|
+
if (money.currency !== other.currency) {
|
|
643
|
+
mismatch(money, other);
|
|
644
|
+
}
|
|
645
|
+
let left = money.minor;
|
|
646
|
+
let right = other.minor;
|
|
647
|
+
if (money.scale !== other.scale) {
|
|
648
|
+
const scale = Math.max(money.scale, other.scale);
|
|
649
|
+
left = scaleUp(left, scale - money.scale);
|
|
650
|
+
right = scaleUp(right, scale - other.scale);
|
|
651
|
+
}
|
|
652
|
+
// number < bigint comparisons are exact in JS
|
|
653
|
+
if (left < right) {
|
|
654
|
+
return -1;
|
|
655
|
+
}
|
|
656
|
+
return left > right ? 1 : 0;
|
|
657
|
+
}
|
|
658
|
+
|
|
659
|
+
/**
|
|
660
|
+
* Same currency and same value (1.0 EUR at scale 1 equals 1.00 EUR). Different currencies: false.
|
|
661
|
+
*/
|
|
662
|
+
export function equals(money: Money, other: Money): boolean {
|
|
663
|
+
if (money.currency !== other.currency) {
|
|
664
|
+
return false;
|
|
665
|
+
}
|
|
666
|
+
if (money.scale === other.scale) {
|
|
667
|
+
// == compares number and bigint exactly
|
|
668
|
+
return money.minor == other.minor;
|
|
669
|
+
}
|
|
670
|
+
return compare(money, other) === 0;
|
|
671
|
+
}
|
|
672
|
+
|
|
673
|
+
/** money < other (same currency; any scale). */
|
|
674
|
+
export const lessThan = <C extends string>(money: Money<C>, other: Money<NoInfer<C>>): boolean =>
|
|
675
|
+
compare(money, other) < 0;
|
|
676
|
+
/** money <= other */
|
|
677
|
+
export const lessThanOrEqual = <C extends string>(
|
|
678
|
+
money: Money<C>,
|
|
679
|
+
other: Money<NoInfer<C>>,
|
|
680
|
+
): boolean => compare(money, other) <= 0;
|
|
681
|
+
/** money > other */
|
|
682
|
+
export const greaterThan = <C extends string>(money: Money<C>, other: Money<NoInfer<C>>): boolean =>
|
|
683
|
+
compare(money, other) > 0;
|
|
684
|
+
/** money >= other */
|
|
685
|
+
export const greaterThanOrEqual = <C extends string>(
|
|
686
|
+
money: Money<C>,
|
|
687
|
+
other: Money<NoInfer<C>>,
|
|
688
|
+
): boolean => compare(money, other) >= 0;
|
|
689
|
+
|
|
690
|
+
/** Whether the amount is zero. */
|
|
691
|
+
export const isZero = (money: Money): boolean => money.minor == 0;
|
|
692
|
+
/** Whether the amount is greater than zero. */
|
|
693
|
+
export const isPositive = (money: Money): boolean => money.minor > 0;
|
|
694
|
+
/** Whether the amount is less than zero. */
|
|
695
|
+
export const isNegative = (money: Money): boolean => money.minor < 0;
|
|
696
|
+
/** 1, 0 or -1 for positive, zero and negative amounts. */
|
|
697
|
+
export const sign = (money: Money): -1 | 0 | 1 => {
|
|
698
|
+
if (money.minor > 0) {
|
|
699
|
+
return 1;
|
|
700
|
+
}
|
|
701
|
+
return money.minor < 0 ? -1 : 0;
|
|
702
|
+
};
|
|
703
|
+
|
|
704
|
+
/** The smallest of the amounts (same currency); the first one wins ties. */
|
|
705
|
+
export function min<C extends string>(first: Money<C>, ...rest: Money<NoInfer<C>>[]): Money<C> {
|
|
706
|
+
let smallest = first;
|
|
707
|
+
for (const candidate of rest) {
|
|
708
|
+
if (compare(candidate, smallest) < 0) {
|
|
709
|
+
smallest = candidate;
|
|
710
|
+
}
|
|
711
|
+
}
|
|
712
|
+
return smallest;
|
|
713
|
+
}
|
|
714
|
+
/** The largest of the amounts (same currency); the first one wins ties. */
|
|
715
|
+
export function max<C extends string>(first: Money<C>, ...rest: Money<NoInfer<C>>[]): Money<C> {
|
|
716
|
+
let largest = first;
|
|
717
|
+
for (const candidate of rest) {
|
|
718
|
+
if (compare(candidate, largest) > 0) {
|
|
719
|
+
largest = candidate;
|
|
720
|
+
}
|
|
721
|
+
}
|
|
722
|
+
return largest;
|
|
723
|
+
}
|
|
724
|
+
/** Limits m to [lo, hi]. */
|
|
725
|
+
export function clamp<C extends string>(
|
|
726
|
+
money: Money<C>,
|
|
727
|
+
lo: Money<NoInfer<C>>,
|
|
728
|
+
hi: Money<NoInfer<C>>,
|
|
729
|
+
): Money<C> {
|
|
730
|
+
if (compare(lo, hi) > 0) {
|
|
731
|
+
throw new RangeError('clamp(): lo > hi');
|
|
732
|
+
}
|
|
733
|
+
if (compare(money, lo) < 0) {
|
|
734
|
+
return lo;
|
|
735
|
+
}
|
|
736
|
+
return compare(money, hi) > 0 ? hi : money;
|
|
737
|
+
}
|
|
738
|
+
|
|
739
|
+
// ---------------------------------------------------------------------------------------------
|
|
740
|
+
// Serialisation primitives
|
|
741
|
+
// ---------------------------------------------------------------------------------------------
|
|
742
|
+
|
|
743
|
+
/**
|
|
744
|
+
* Exact decimal string in major units: "12.34", "-0.05", "1000" (JPY). For NUMERIC/DECIMAL columns.
|
|
745
|
+
*/
|
|
746
|
+
export function toDecimal(money: Money): string {
|
|
747
|
+
return formatScaled(money.minor, money.scale);
|
|
748
|
+
}
|
|
749
|
+
|
|
750
|
+
/** Minor units as a bigint (always safe; use for BIGINT columns). */
|
|
751
|
+
export function toMinor(money: Money): bigint {
|
|
752
|
+
return toBigInt(money.minor);
|
|
753
|
+
}
|
|
754
|
+
|
|
755
|
+
/** Minor units as a number; throws if not a safe integer. */
|
|
756
|
+
export function toMinorNumber(money: Money): number {
|
|
757
|
+
if (typeof money.minor === 'bigint') {
|
|
758
|
+
throw new RangeError(`${money} does not fit in a safe integer; use toMinor()`);
|
|
759
|
+
}
|
|
760
|
+
return money.minor;
|
|
761
|
+
}
|
|
762
|
+
|
|
763
|
+
/** Parses `{ amount: "12.34", currency: "EUR" }` (as produced by JSON.stringify(money)). */
|
|
764
|
+
export function fromJSON<C extends CurrencyInput = CurrencyInput>(
|
|
765
|
+
json: MoneyJSON<C> | string,
|
|
766
|
+
options?: MoneyOptions,
|
|
767
|
+
): Money<C> {
|
|
768
|
+
const parsed = typeof json === 'string' ? (JSON.parse(json) as MoneyJSON<C>) : json;
|
|
769
|
+
if (
|
|
770
|
+
parsed === null ||
|
|
771
|
+
typeof parsed !== 'object' ||
|
|
772
|
+
typeof parsed.amount !== 'string' ||
|
|
773
|
+
typeof parsed.currency !== 'string'
|
|
774
|
+
) {
|
|
775
|
+
throw new TypeError('Expected { amount: string, currency: string }');
|
|
776
|
+
}
|
|
777
|
+
return money(parsed.amount, parsed.currency, options);
|
|
778
|
+
}
|
|
779
|
+
|
|
780
|
+
export type { Factor, Ratio } from './decimal.js';
|
|
781
|
+
export { ratio } from './decimal.js';
|