@vielzeug/coins 2.1.1 → 3.0.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/README.md +12 -67
- package/dist/_decimal.cjs +2 -0
- package/dist/_decimal.cjs.map +1 -0
- package/dist/{decimal.d.ts → _decimal.d.ts} +2 -1
- package/dist/_decimal.d.ts.map +1 -0
- package/dist/_decimal.js +64 -0
- package/dist/_decimal.js.map +1 -0
- package/dist/aggregate.cjs +1 -1
- package/dist/aggregate.cjs.map +1 -1
- package/dist/aggregate.d.ts.map +1 -1
- package/dist/aggregate.js +34 -30
- package/dist/aggregate.js.map +1 -1
- package/dist/coins.cjs +1 -1
- package/dist/coins.cjs.map +1 -1
- package/dist/coins.iife.js +1 -1
- package/dist/coins.iife.js.map +1 -1
- package/dist/coins.js +1 -1
- package/dist/coins.js.map +1 -1
- package/dist/currency.cjs +1 -1
- package/dist/currency.cjs.map +1 -1
- package/dist/currency.d.ts +3 -4
- package/dist/currency.d.ts.map +1 -1
- package/dist/currency.js +21 -40
- package/dist/currency.js.map +1 -1
- package/dist/errors.cjs +1 -1
- package/dist/errors.cjs.map +1 -1
- package/dist/errors.d.ts +4 -1
- package/dist/errors.d.ts.map +1 -1
- package/dist/errors.js +16 -5
- package/dist/errors.js.map +1 -1
- package/dist/exchange.cjs +1 -1
- package/dist/exchange.cjs.map +1 -1
- package/dist/exchange.d.ts +1 -0
- package/dist/exchange.d.ts.map +1 -1
- package/dist/exchange.js +13 -13
- package/dist/exchange.js.map +1 -1
- package/dist/format.cjs +1 -1
- package/dist/format.cjs.map +1 -1
- package/dist/format.d.ts.map +1 -1
- package/dist/format.js +54 -52
- package/dist/format.js.map +1 -1
- package/dist/index.cjs +1 -1
- package/dist/index.d.ts +4 -4
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +6 -6
- package/dist/money.cjs +1 -1
- package/dist/money.cjs.map +1 -1
- package/dist/money.d.ts +13 -5
- package/dist/money.d.ts.map +1 -1
- package/dist/money.js +77 -65
- package/dist/money.js.map +1 -1
- package/dist/serialization.cjs +1 -1
- package/dist/serialization.cjs.map +1 -1
- package/dist/serialization.d.ts +1 -4
- package/dist/serialization.d.ts.map +1 -1
- package/dist/serialization.js +6 -38
- package/dist/serialization.js.map +1 -1
- package/package.json +8 -7
- package/dist/decimal.cjs +0 -2
- package/dist/decimal.cjs.map +0 -1
- package/dist/decimal.d.ts.map +0 -1
- package/dist/decimal.js +0 -52
- package/dist/decimal.js.map +0 -1
package/README.md
CHANGED
|
@@ -1,14 +1,16 @@
|
|
|
1
1
|
# @vielzeug/coins
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
> Currency formatting and exchange utilities for monetary arithmetic
|
|
4
4
|
|
|
5
|
-
##
|
|
5
|
+
## Installation
|
|
6
6
|
|
|
7
7
|
```sh
|
|
8
8
|
pnpm add @vielzeug/coins
|
|
9
|
+
npm install @vielzeug/coins
|
|
10
|
+
yarn add @vielzeug/coins
|
|
9
11
|
```
|
|
10
12
|
|
|
11
|
-
## Start
|
|
13
|
+
## Quick Start
|
|
12
14
|
|
|
13
15
|
```ts
|
|
14
16
|
import { USD, add, money, toDecimal } from '@vielzeug/coins';
|
|
@@ -18,71 +20,14 @@ const subtotal = add(money('12.50', USD), money('7.25', USD));
|
|
|
18
20
|
console.log(toDecimal(subtotal)); // '19.75'
|
|
19
21
|
```
|
|
20
22
|
|
|
21
|
-
|
|
23
|
+
## Documentation
|
|
22
24
|
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
## Core API
|
|
30
|
-
|
|
31
|
-
```ts
|
|
32
|
-
import {
|
|
33
|
-
EUR,
|
|
34
|
-
USD,
|
|
35
|
-
allocate,
|
|
36
|
-
exchange,
|
|
37
|
-
exchangeRate,
|
|
38
|
-
format,
|
|
39
|
-
money,
|
|
40
|
-
multiply,
|
|
41
|
-
sum,
|
|
42
|
-
toDecimal,
|
|
43
|
-
} from '@vielzeug/coins';
|
|
44
|
-
|
|
45
|
-
const items = [money('12.50', USD), money('7.25', USD)];
|
|
46
|
-
const subtotal = sum(items);
|
|
47
|
-
const total = multiply(subtotal, '1.08', { rounding: 'halfEven' });
|
|
48
|
-
const shares = allocate(total, 3);
|
|
49
|
-
|
|
50
|
-
const usdToEur = exchangeRate({ from: USD, to: EUR, value: '0.9234' });
|
|
51
|
-
const eurTotal = exchange(total, usdToEur, { rounding: 'halfEven' });
|
|
52
|
-
|
|
53
|
-
console.log(format(eurTotal, { locale: 'de-DE' }));
|
|
54
|
-
console.log(shares.map(toDecimal));
|
|
55
|
-
```
|
|
56
|
-
|
|
57
|
-
## Currency Definitions
|
|
58
|
-
|
|
59
|
-
Built-in definitions: `USD`, `EUR`, `GBP`, `JPY`, `KRW`, `BHD`, `KWD`.
|
|
60
|
-
|
|
61
|
-
Define a business currency explicitly when required:
|
|
62
|
-
|
|
63
|
-
```ts
|
|
64
|
-
import { defineCurrency, money } from '@vielzeug/coins';
|
|
65
|
-
|
|
66
|
-
const POINTS = defineCurrency({ code: 'PTS', minorUnit: 0 });
|
|
67
|
-
const balance = money('250', POINTS);
|
|
68
|
-
```
|
|
69
|
-
|
|
70
|
-
## Errors
|
|
71
|
-
|
|
72
|
-
All failures extend `CoinsError` and expose `code`.
|
|
73
|
-
|
|
74
|
-
```ts
|
|
75
|
-
import { CoinsError, money, USD } from '@vielzeug/coins';
|
|
76
|
-
|
|
77
|
-
try {
|
|
78
|
-
money('19.999', USD);
|
|
79
|
-
} catch (error) {
|
|
80
|
-
if (error instanceof CoinsError && error.code === 'INVALID_MONEY') {
|
|
81
|
-
// Over-precise decimal requires a rounding mode.
|
|
82
|
-
}
|
|
83
|
-
}
|
|
84
|
-
```
|
|
25
|
+
- [Overview](https://vielzeug.dev/coins/)
|
|
26
|
+
- [Usage Guide](https://vielzeug.dev/coins/usage)
|
|
27
|
+
- [API Reference](https://vielzeug.dev/coins/api)
|
|
28
|
+
- [Examples](https://vielzeug.dev/coins/examples)
|
|
29
|
+
- [Migration Guide](https://vielzeug.dev/coins/migration)
|
|
85
30
|
|
|
86
31
|
## License
|
|
87
32
|
|
|
88
|
-
MIT © Helmuth Saatkamp
|
|
33
|
+
MIT © [Helmuth Saatkamp](https://github.com/helmuthdu) — part of the [Vielzeug](https://github.com/helmuthdu/vielzeug) monorepo.
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
const e=require("./errors.cjs");var t=/^(-?)(\d+)(?:\.(\d+))?$/,n=1e3,r=100,i=new Set([`awayFromZero`,`ceil`,`floor`,`halfAwayFromZero`,`halfEven`,`towardZero`]);function a(t){if(!i.has(t))throw new e.CoinsError(`INVALID_ROUNDING`,`Unknown rounding mode: ${String(t)}`)}function o(i){if(typeof i!=`string`)throw new e.CoinsError(`INVALID_DECIMAL`,`Decimal input must be a string`);if(i.length>n)throw new e.CoinsError(`INVALID_DECIMAL`,`Decimal input is too long`);let a=t.exec(i);if(!a)throw new e.CoinsError(`INVALID_DECIMAL`,`Invalid decimal: "${i}"`);let o=(a[3]??``).replace(/0+$/,``);if(o.length>r)throw new e.CoinsError(`INVALID_DECIMAL`,`Decimal precision cannot exceed ${r} places`);let s=10n**BigInt(o.length),c=BigInt(a[2])*s+BigInt(o||`0`),u=a[1]===`-`&&c!==0n?-c:c,d=l(u<0n?-u:u,s);return Object.freeze({denominator:s/d,numerator:u/d})}function s(t,n,r){if(a(r),n<=0n)throw new e.CoinsError(`INVALID_DECIMAL`,`Decimal denominator must be positive`);let i=t<0n,o=i?-t:t,s=o/n,c=o%n;if(c===0n)return i?-s:s;let l=(()=>{switch(r){case`awayFromZero`:return!0;case`ceil`:return!i;case`floor`:return i;case`halfAwayFromZero`:return c*2n>=n;case`halfEven`:{let e=c*2n;return e>n||e===n&&s%2n!=0n}case`towardZero`:return!1;default:throw new e.CoinsError(`INVALID_ROUNDING`,`Unknown rounding mode: ${r}`)}})()?s+1n:s;return i?-l:l}function c(e,t){let n=e<0n,r=n?-e:e,i=10n**BigInt(t),a=r/i;if(t===0)return`${n?`-`:``}${a}`;let o=(r%i).toString().padStart(t,`0`);return`${n?`-`:``}${a}.${o}`}function l(e,t){let n=e,r=t;for(;r!==0n;)[n,r]=[r,n%r];return n===0n?1n:n}function u(e,t){return e/l(e,t)*t}exports.assertRoundingMode=a,exports.decimal=o,exports.gcd=l,exports.lcm=u,exports.roundDivision=s,exports.toDecimalString=c;
|
|
2
|
+
//# sourceMappingURL=_decimal.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"_decimal.cjs","names":[],"sources":["../src/_decimal.ts"],"sourcesContent":["import { CoinsError } from './errors';\nimport type { Decimal, RoundingMode } from './types';\n\nconst DECIMAL = /^(-?)(\\d+)(?:\\.(\\d+))?$/;\nconst MAX_DECIMAL_DIGITS = 1000;\nconst MAX_DECIMAL_PLACES = 100;\nconst ROUNDING_MODES = new Set<RoundingMode>([\n 'awayFromZero',\n 'ceil',\n 'floor',\n 'halfAwayFromZero',\n 'halfEven',\n 'towardZero',\n]);\n\nexport function assertRoundingMode(value: unknown): asserts value is RoundingMode {\n if (!ROUNDING_MODES.has(value as RoundingMode)) {\n throw new CoinsError('INVALID_ROUNDING', `Unknown rounding mode: ${String(value)}`);\n }\n}\n\nexport function decimal(value: string): Decimal {\n if (typeof value !== 'string') throw new CoinsError('INVALID_DECIMAL', 'Decimal input must be a string');\n if (value.length > MAX_DECIMAL_DIGITS) throw new CoinsError('INVALID_DECIMAL', 'Decimal input is too long');\n\n const match = DECIMAL.exec(value);\n\n if (!match) throw new CoinsError('INVALID_DECIMAL', `Invalid decimal: \"${value}\"`);\n\n const fraction = (match[3] ?? '').replace(/0+$/, '');\n\n if (fraction.length > MAX_DECIMAL_PLACES) {\n throw new CoinsError('INVALID_DECIMAL', `Decimal precision cannot exceed ${MAX_DECIMAL_PLACES} places`);\n }\n\n const denominator = 10n ** BigInt(fraction.length);\n const unsigned = BigInt(match[2]!) * denominator + BigInt(fraction || '0');\n const numerator = match[1] === '-' && unsigned !== 0n ? -unsigned : unsigned;\n const divisor = gcd(numerator < 0n ? -numerator : numerator, denominator);\n\n return Object.freeze({ denominator: denominator / divisor, numerator: numerator / divisor }) as Decimal;\n}\n\nexport function roundDivision(numerator: bigint, denominator: bigint, mode: RoundingMode): bigint {\n assertRoundingMode(mode);\n if (denominator <= 0n) throw new CoinsError('INVALID_DECIMAL', 'Decimal denominator must be positive');\n\n const negative = numerator < 0n;\n const absolute = negative ? -numerator : numerator;\n const quotient = absolute / denominator;\n const remainder = absolute % denominator;\n\n if (remainder === 0n) return negative ? -quotient : quotient;\n\n const increment = (() => {\n switch (mode) {\n case 'awayFromZero':\n return true;\n case 'ceil':\n return !negative;\n case 'floor':\n return negative;\n case 'halfAwayFromZero':\n return remainder * 2n >= denominator;\n case 'halfEven': {\n const doubled = remainder * 2n;\n\n return doubled > denominator || (doubled === denominator && quotient % 2n !== 0n);\n }\n case 'towardZero':\n return false;\n default:\n throw new CoinsError('INVALID_ROUNDING', `Unknown rounding mode: ${mode satisfies never}`);\n }\n })();\n\n const result = increment ? quotient + 1n : quotient;\n\n return negative ? -result : result;\n}\n\nexport function toDecimalString(amount: bigint, minorUnit: number): string {\n const negative = amount < 0n;\n const absolute = negative ? -amount : amount;\n const scale = 10n ** BigInt(minorUnit);\n const whole = absolute / scale;\n\n if (minorUnit === 0) return `${negative ? '-' : ''}${whole}`;\n\n const fraction = (absolute % scale).toString().padStart(minorUnit, '0');\n\n return `${negative ? '-' : ''}${whole}.${fraction}`;\n}\n\nexport function gcd(left: bigint, right: bigint): bigint {\n let a = left;\n let b = right;\n\n while (b !== 0n) [a, b] = [b, a % b];\n\n return a === 0n ? 1n : a;\n}\n\nexport function lcm(left: bigint, right: bigint): bigint {\n return (left / gcd(left, right)) * right;\n}\n"],"mappings":"gCAGA,IAAM,EAAU,0BACV,EAAqB,IACrB,EAAqB,IACrB,EAAiB,IAAI,IAAkB,CAC3C,eACA,OACA,QACA,mBACA,W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AO,CAAC,EACV,IAAK,QACH,OAAO,EACT,IAAK,mBACH,OAAO,EAAY,IAAM,EAC3B,IAAK,WAAY,CACf,IAAM,EAAU,EAAY,GAE5B,OAAO,EAAU,GAAgB,IAAY,GAAe,EAAW,IAAO,EAChF,CACA,IAAK,aACH,MAAO,GACT,QACE,MAAM,IAAI,EAAA,WAAW,mBAAoB,0BAA0B,GAAsB,CAC7F,CACF,EAAA,CAEe,EAAY,EAAW,GAAK,EAE3C,OAAO,EAAW,CAAC,EAAS,CAC9B,CAEA,SAAgB,EAAgB,EAAgB,EAA2B,CACzE,IAAM,EAAW,EAAS,GACpB,EAAW,EAAW,CAAC,EAAS,EAChC,EAAQ,KAAO,OAAO,CAAS,EAC/B,EAAQ,EAAW,EAEzB,GAAI,IAAc,EAAG,MAAO,GAAG,EAAW,IAAM,KAAK,IAErD,IAAM,GAAY,EAAW,EAAA,CAAO,SAAS,CAAC,CAAC,SAAS,EAAW,GAAG,EAEtE,MAAO,GAAG,EAAW,IAAM,KAAK,EAAM,GAAG,GAC3C,CAEA,SAAgB,EAAI,EAAc,EAAuB,CACvD,IAAI,EAAI,EACJ,EAAI,EAER,KAAO,IAAM,IAAI,CAAC,EAAG,GAAK,CAAC,EAAG,EAAI,CAAC,EAEnC,OAAO,IAAM,GAAK,GAAK,CACzB,CAEA,SAAgB,EAAI,EAAc,EAAuB,CACvD,OAAQ,EAAO,EAAI,EAAM,CAAK,EAAK,CACrC"}
|
|
@@ -1,7 +1,8 @@
|
|
|
1
1
|
import type { Decimal, RoundingMode } from './types';
|
|
2
|
+
export declare function assertRoundingMode(value: unknown): asserts value is RoundingMode;
|
|
2
3
|
export declare function decimal(value: string): Decimal;
|
|
3
4
|
export declare function roundDivision(numerator: bigint, denominator: bigint, mode: RoundingMode): bigint;
|
|
4
5
|
export declare function toDecimalString(amount: bigint, minorUnit: number): string;
|
|
5
6
|
export declare function gcd(left: bigint, right: bigint): bigint;
|
|
6
7
|
export declare function lcm(left: bigint, right: bigint): bigint;
|
|
7
|
-
//# sourceMappingURL=
|
|
8
|
+
//# sourceMappingURL=_decimal.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"_decimal.d.ts","sourceRoot":"","sources":["../src/_decimal.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,OAAO,EAAE,YAAY,EAAE,MAAM,SAAS,CAAC;AAcrD,wBAAgB,kBAAkB,CAAC,KAAK,EAAE,OAAO,GAAG,OAAO,CAAC,KAAK,IAAI,YAAY,CAIhF;AAED,wBAAgB,OAAO,CAAC,KAAK,EAAE,MAAM,GAAG,OAAO,CAoB9C;AAED,wBAAgB,aAAa,CAAC,SAAS,EAAE,MAAM,EAAE,WAAW,EAAE,MAAM,EAAE,IAAI,EAAE,YAAY,GAAG,MAAM,CAoChG;AAED,wBAAgB,eAAe,CAAC,MAAM,EAAE,MAAM,EAAE,SAAS,EAAE,MAAM,GAAG,MAAM,CAWzE;AAED,wBAAgB,GAAG,CAAC,IAAI,EAAE,MAAM,EAAE,KAAK,EAAE,MAAM,GAAG,MAAM,CAOvD;AAED,wBAAgB,GAAG,CAAC,IAAI,EAAE,MAAM,EAAE,KAAK,EAAE,MAAM,GAAG,MAAM,CAEvD"}
|
package/dist/_decimal.js
ADDED
|
@@ -0,0 +1,64 @@
|
|
|
1
|
+
import { CoinsError as e } from "./errors.js";
|
|
2
|
+
//#region src/_decimal.ts
|
|
3
|
+
var t = /^(-?)(\d+)(?:\.(\d+))?$/, n = 1e3, r = 100, i = /* @__PURE__ */ new Set([
|
|
4
|
+
"awayFromZero",
|
|
5
|
+
"ceil",
|
|
6
|
+
"floor",
|
|
7
|
+
"halfAwayFromZero",
|
|
8
|
+
"halfEven",
|
|
9
|
+
"towardZero"
|
|
10
|
+
]);
|
|
11
|
+
function a(t) {
|
|
12
|
+
if (!i.has(t)) throw new e("INVALID_ROUNDING", `Unknown rounding mode: ${String(t)}`);
|
|
13
|
+
}
|
|
14
|
+
function o(i) {
|
|
15
|
+
if (typeof i != "string") throw new e("INVALID_DECIMAL", "Decimal input must be a string");
|
|
16
|
+
if (i.length > n) throw new e("INVALID_DECIMAL", "Decimal input is too long");
|
|
17
|
+
let a = t.exec(i);
|
|
18
|
+
if (!a) throw new e("INVALID_DECIMAL", `Invalid decimal: "${i}"`);
|
|
19
|
+
let o = (a[3] ?? "").replace(/0+$/, "");
|
|
20
|
+
if (o.length > r) throw new e("INVALID_DECIMAL", `Decimal precision cannot exceed ${r} places`);
|
|
21
|
+
let s = 10n ** BigInt(o.length), c = BigInt(a[2]) * s + BigInt(o || "0"), u = a[1] === "-" && c !== 0n ? -c : c, d = l(u < 0n ? -u : u, s);
|
|
22
|
+
return Object.freeze({
|
|
23
|
+
denominator: s / d,
|
|
24
|
+
numerator: u / d
|
|
25
|
+
});
|
|
26
|
+
}
|
|
27
|
+
function s(t, n, r) {
|
|
28
|
+
if (a(r), n <= 0n) throw new e("INVALID_DECIMAL", "Decimal denominator must be positive");
|
|
29
|
+
let i = t < 0n, o = i ? -t : t, s = o / n, c = o % n;
|
|
30
|
+
if (c === 0n) return i ? -s : s;
|
|
31
|
+
let l = (() => {
|
|
32
|
+
switch (r) {
|
|
33
|
+
case "awayFromZero": return !0;
|
|
34
|
+
case "ceil": return !i;
|
|
35
|
+
case "floor": return i;
|
|
36
|
+
case "halfAwayFromZero": return c * 2n >= n;
|
|
37
|
+
case "halfEven": {
|
|
38
|
+
let e = c * 2n;
|
|
39
|
+
return e > n || e === n && s % 2n != 0n;
|
|
40
|
+
}
|
|
41
|
+
case "towardZero": return !1;
|
|
42
|
+
default: throw new e("INVALID_ROUNDING", `Unknown rounding mode: ${r}`);
|
|
43
|
+
}
|
|
44
|
+
})() ? s + 1n : s;
|
|
45
|
+
return i ? -l : l;
|
|
46
|
+
}
|
|
47
|
+
function c(e, t) {
|
|
48
|
+
let n = e < 0n, r = n ? -e : e, i = 10n ** BigInt(t), a = r / i;
|
|
49
|
+
if (t === 0) return `${n ? "-" : ""}${a}`;
|
|
50
|
+
let o = (r % i).toString().padStart(t, "0");
|
|
51
|
+
return `${n ? "-" : ""}${a}.${o}`;
|
|
52
|
+
}
|
|
53
|
+
function l(e, t) {
|
|
54
|
+
let n = e, r = t;
|
|
55
|
+
for (; r !== 0n;) [n, r] = [r, n % r];
|
|
56
|
+
return n === 0n ? 1n : n;
|
|
57
|
+
}
|
|
58
|
+
function u(e, t) {
|
|
59
|
+
return e / l(e, t) * t;
|
|
60
|
+
}
|
|
61
|
+
//#endregion
|
|
62
|
+
export { a as assertRoundingMode, o as decimal, l as gcd, u as lcm, s as roundDivision, c as toDecimalString };
|
|
63
|
+
|
|
64
|
+
//# sourceMappingURL=_decimal.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"_decimal.js","names":[],"sources":["../src/_decimal.ts"],"sourcesContent":["import { CoinsError } from './errors';\nimport type { Decimal, RoundingMode } from './types';\n\nconst DECIMAL = /^(-?)(\\d+)(?:\\.(\\d+))?$/;\nconst MAX_DECIMAL_DIGITS = 1000;\nconst MAX_DECIMAL_PLACES = 100;\nconst ROUNDING_MODES = new Set<RoundingMode>([\n 'awayFromZero',\n 'ceil',\n 'floor',\n 'halfAwayFromZero',\n 'halfEven',\n 'towardZero',\n]);\n\nexport function assertRoundingMode(value: unknown): asserts value is RoundingMode {\n if (!ROUNDING_MODES.has(value as RoundingMode)) {\n throw new CoinsError('INVALID_ROUNDING', `Unknown rounding mode: ${String(value)}`);\n }\n}\n\nexport function decimal(value: string): Decimal {\n if (typeof value !== 'string') throw new CoinsError('INVALID_DECIMAL', 'Decimal input must be a string');\n if (value.length > MAX_DECIMAL_DIGITS) throw new CoinsError('INVALID_DECIMAL', 'Decimal input is too long');\n\n const match = DECIMAL.exec(value);\n\n if (!match) throw new CoinsError('INVALID_DECIMAL', `Invalid decimal: \"${value}\"`);\n\n const fraction = (match[3] ?? '').replace(/0+$/, '');\n\n if (fraction.length > MAX_DECIMAL_PLACES) {\n throw new CoinsError('INVALID_DECIMAL', `Decimal precision cannot exceed ${MAX_DECIMAL_PLACES} places`);\n }\n\n const denominator = 10n ** BigInt(fraction.length);\n const unsigned = BigInt(match[2]!) * denominator + BigInt(fraction || '0');\n const numerator = match[1] === '-' && unsigned !== 0n ? -unsigned : unsigned;\n const divisor = gcd(numerator < 0n ? -numerator : numerator, denominator);\n\n return Object.freeze({ denominator: denominator / divisor, numerator: numerator / divisor }) as Decimal;\n}\n\nexport function roundDivision(numerator: bigint, denominator: bigint, mode: RoundingMode): bigint {\n assertRoundingMode(mode);\n if (denominator <= 0n) throw new CoinsError('INVALID_DECIMAL', 'Decimal denominator must be positive');\n\n const negative = numerator < 0n;\n const absolute = negative ? -numerator : numerator;\n const quotient = absolute / denominator;\n const remainder = absolute % denominator;\n\n if (remainder === 0n) return negative ? -quotient : quotient;\n\n const increment = (() => {\n switch (mode) {\n case 'awayFromZero':\n return true;\n case 'ceil':\n return !negative;\n case 'floor':\n return negative;\n case 'halfAwayFromZero':\n return remainder * 2n >= denominator;\n case 'halfEven': {\n const doubled = remainder * 2n;\n\n return doubled > denominator || (doubled === denominator && quotient % 2n !== 0n);\n }\n case 'towardZero':\n return false;\n default:\n throw new CoinsError('INVALID_ROUNDING', `Unknown rounding mode: ${mode satisfies never}`);\n }\n })();\n\n const result = increment ? quotient + 1n : quotient;\n\n return negative ? -result : result;\n}\n\nexport function toDecimalString(amount: bigint, minorUnit: number): string {\n const negative = amount < 0n;\n const absolute = negative ? -amount : amount;\n const scale = 10n ** BigInt(minorUnit);\n const whole = absolute / scale;\n\n if (minorUnit === 0) return `${negative ? '-' : ''}${whole}`;\n\n const fraction = (absolute % scale).toString().padStart(minorUnit, '0');\n\n return `${negative ? '-' : ''}${whole}.${fraction}`;\n}\n\nexport function gcd(left: bigint, right: bigint): bigint {\n let a = left;\n let b = right;\n\n while (b !== 0n) [a, b] = [b, a % b];\n\n return a === 0n ? 1n : a;\n}\n\nexport function lcm(left: bigint, right: bigint): bigint {\n return (left / gcd(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C,IAAW;CAwBpD,IAAM,WAtBmB;EACvB,QAAQ,GAAR;GACE,KAAK,gBACH,OAAO;GACT,KAAK,QACH,OAAO,CAAC;GACV,KAAK,SACH,OAAO;GACT,KAAK,oBACH,OAAO,IAAY,MAAM;GAC3B,KAAK,YAAY;IACf,IAAM,IAAU,IAAY;IAE5B,OAAO,IAAU,KAAgB,MAAY,KAAe,IAAW,MAAO;GAChF;GACA,KAAK,cACH,OAAO;GACT,SACE,MAAM,IAAI,EAAW,oBAAoB,0BAA0B,GAAsB;EAC7F;CACF,EAAA,CAEe,IAAY,IAAW,KAAK;CAE3C,OAAO,IAAW,CAAC,IAAS;AAC9B;AAEA,SAAgB,EAAgB,GAAgB,GAA2B;CACzE,IAAM,IAAW,IAAS,IACpB,IAAW,IAAW,CAAC,IAAS,GAChC,IAAQ,OAAO,OAAO,CAAS,GAC/B,IAAQ,IAAW;CAEzB,IAAI,MAAc,GAAG,OAAO,GAAG,IAAW,MAAM,KAAK;CAErD,IAAM,KAAY,IAAW,EAAA,CAAO,SAAS,CAAC,CAAC,SAAS,GAAW,GAAG;CAEtE,OAAO,GAAG,IAAW,MAAM,KAAK,EAAM,GAAG;AAC3C;AAEA,SAAgB,EAAI,GAAc,GAAuB;CACvD,IAAI,IAAI,GACJ,IAAI;CAER,OAAO,MAAM,KAAI,CAAC,GAAG,KAAK,CAAC,GAAG,IAAI,CAAC;CAEnC,OAAO,MAAM,KAAK,KAAK;AACzB;AAEA,SAAgB,EAAI,GAAc,GAAuB;CACvD,OAAQ,IAAO,EAAI,GAAM,CAAK,IAAK;AACrC"}
|
package/dist/aggregate.cjs
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
const e=require("./errors.cjs"),t=require("./
|
|
1
|
+
const e=require("./errors.cjs"),t=require("./_decimal.cjs"),n=require("./currency.cjs"),r=require("./money.cjs");var i=1e5;function a(t,i){if(i&&!n.isCurrency(i.currency))throw new e.CoinsError(`INVALID_CURRENCY`,`sum() requires a canonical currency`);let a=0n,o=i?.currency;for(let n of t){if(r.assertMoney(n),o===void 0)o=n.currency;else if(n.currency!==o)throw new e.CurrencyMismatchError(o.code,n.currency.code);a+=n.amount}if(o===void 0)throw new e.CoinsError(`INVALID_MONEY`,`sum() of empty iterable requires { currency }`);return r.createMoney(a,o)}function o(n,a){if(r.assertMoney(n),typeof a==`number`)return s(n,a);if(!Array.isArray(a))throw new e.CoinsError(`INVALID_ALLOCATION`,`Allocation weights must be an array`);if(a.length===0)throw new e.CoinsError(`INVALID_ALLOCATION`,`Allocation weights cannot be empty`);if(a.length>i)throw new e.CoinsError(`INVALID_ALLOCATION`,`Allocation cannot exceed ${i} parts`);for(let t=0;t<a.length;t++)if(!Object.hasOwn(a,t))throw new e.CoinsError(`INVALID_ALLOCATION`,`Allocation weights cannot contain empty slots`);let o=a.map(t.decimal);if(o.some(e=>e.numerator<0n))throw new e.CoinsError(`INVALID_ALLOCATION`,`Allocation weights cannot be negative`);let c=o.reduce((e,n)=>t.lcm(e,n.denominator),1n),l=o.map(e=>e.numerator*(c/e.denominator)),u=l.reduce((e,t)=>e+t,0n);if(u===0n)throw new e.CoinsError(`INVALID_ALLOCATION`,`Allocation weights must include a positive value`);let d=n.amount<0n?-1n:1n,f=n.amount<0n?-n.amount:n.amount,p=l.map(e=>f*e/u),m=f-p.reduce((e,t)=>e+t,0n),h=l.map((e,t)=>({index:t,remainder:f*e%u})).sort((e,t)=>e.remainder===t.remainder?e.index-t.index:e.remainder>t.remainder?-1:1);for(let e of h){if(m===0n)break;p[e.index]+=1n,m-=1n}return p.map(e=>r.createMoney(e*d,n.currency))}function s(t,n){if(!Number.isSafeInteger(n)||n<1||n>i)throw new e.CoinsError(`INVALID_ALLOCATION`,`Allocation count must be a positive safe integer no greater than ${i}`);let a=BigInt(n),o=t.amount<0n?-1n:1n,s=t.amount<0n?-t.amount:t.amount,c=s/a,l=s%a;return Array.from({length:n},(e,n)=>r.createMoney((c+(BigInt(n)<l?1n:0n))*o,t.currency))}exports.allocate=o,exports.sum=a;
|
|
2
2
|
//# sourceMappingURL=aggregate.cjs.map
|
package/dist/aggregate.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"aggregate.cjs","names":[],"sources":["../src/aggregate.ts"],"sourcesContent":["import { decimal, lcm } from './
|
|
1
|
+
{"version":3,"file":"aggregate.cjs","names":[],"sources":["../src/aggregate.ts"],"sourcesContent":["import { decimal, lcm } from './_decimal';\nimport { isCurrency } from './currency';\nimport { CoinsError, CurrencyMismatchError } from './errors';\nimport { assertMoney, createMoney } from './money';\nimport type { Currency, Money } from './types';\n\nconst MAX_ALLOCATION_PARTS = 100_000;\n\nexport function sum<C extends Currency>(values: readonly Money<C>[]): Money<C>;\nexport function sum<C extends Currency>(values: Iterable<Money<C>>, options: { currency: C }): Money<C>;\nexport function sum<C extends Currency>(values: Iterable<Money<C>>, options?: { currency: C }): Money<C> {\n if (options && !isCurrency(options.currency)) {\n throw new CoinsError('INVALID_CURRENCY', 'sum() requires a canonical currency');\n }\n\n let amount = 0n;\n let currency: C | undefined = options?.currency;\n\n for (const value of values) {\n assertMoney(value);\n\n if (currency === undefined) {\n currency = value.currency;\n } else if (value.currency !== currency) {\n throw new CurrencyMismatchError(currency.code, value.currency.code);\n }\n\n amount += value.amount;\n }\n\n if (currency === undefined) throw new CoinsError('INVALID_MONEY', 'sum() of empty iterable requires { currency }');\n\n return createMoney(amount, currency);\n}\n\nexport function allocate<C extends Currency>(value: Money<C>, count: number): Money<C>[];\nexport function allocate<C extends Currency>(value: Money<C>, weights: readonly string[]): Money<C>[];\nexport function allocate<C extends Currency>(value: Money<C>, weightsOrCount: number | readonly string[]): Money<C>[] {\n assertMoney(value);\n\n if (typeof weightsOrCount === 'number') return allocateEvenly(value, weightsOrCount);\n\n if (!Array.isArray(weightsOrCount)) {\n throw new CoinsError('INVALID_ALLOCATION', 'Allocation weights must be an array');\n }\n if (weightsOrCount.length === 0) throw new CoinsError('INVALID_ALLOCATION', 'Allocation weights cannot be empty');\n if (weightsOrCount.length > MAX_ALLOCATION_PARTS) {\n throw new CoinsError('INVALID_ALLOCATION', `Allocation cannot exceed ${MAX_ALLOCATION_PARTS} parts`);\n }\n for (let index = 0; index < weightsOrCount.length; index++) {\n if (!Object.hasOwn(weightsOrCount, index)) {\n throw new CoinsError('INVALID_ALLOCATION', 'Allocation weights cannot contain empty slots');\n }\n }\n\n const weights = weightsOrCount.map(decimal);\n\n if (weights.some((weight) => weight.numerator < 0n)) {\n throw new CoinsError('INVALID_ALLOCATION', 'Allocation weights cannot be negative');\n }\n\n const commonDenominator = weights.reduce((result, weight) => lcm(result, weight.denominator), 1n);\n const scaledWeights = weights.map((weight) => weight.numerator * (commonDenominator / weight.denominator));\n const totalWeight = scaledWeights.reduce((result, weight) => result + weight, 0n);\n\n if (totalWeight === 0n)\n throw new CoinsError('INVALID_ALLOCATION', 'Allocation weights must include a positive value');\n\n const sign = value.amount < 0n ? -1n : 1n;\n const absolute = value.amount < 0n ? -value.amount : value.amount;\n const shares = scaledWeights.map((weight) => (absolute * weight) / totalWeight);\n let remainder = absolute - shares.reduce((result, amount) => result + amount, 0n);\n const ranked = scaledWeights\n .map((weight, index) => ({ index, remainder: (absolute * weight) % totalWeight }))\n .sort((left, right) =>\n left.remainder === right.remainder ? left.index - right.index : left.remainder > right.remainder ? -1 : 1,\n );\n\n for (const entry of ranked) {\n if (remainder === 0n) break;\n\n shares[entry.index]! += 1n;\n remainder -= 1n;\n }\n\n return shares.map((amount) => createMoney(amount * sign, value.currency));\n}\n\nfunction allocateEvenly<C extends Currency>(value: Money<C>, countValue: number): Money<C>[] {\n if (!Number.isSafeInteger(countValue) || countValue < 1 || countValue > MAX_ALLOCATION_PARTS) {\n throw new CoinsError(\n 'INVALID_ALLOCATION',\n `Allocation count must be a positive safe integer no greater than ${MAX_ALLOCATION_PARTS}`,\n );\n }\n\n const count = BigInt(countValue);\n const sign = value.amount < 0n ? -1n : 1n;\n const absolute = value.amount < 0n ? -value.amount : value.amount;\n const base = absolute / count;\n const remainder = absolute % count;\n\n return Array.from({ length: countValue }, (_, index) =>\n createMoney((base + (BigInt(index) < remainder ? 1n : 0n)) * sign, value.currency),\n );\n}\n"],"mappings":"iHAMA,IAAM,EAAuB,IAI7B,SAAgB,EAAwB,EAA4B,EAAqC,CACvG,GAAI,GAAW,CAAC,EAAA,WAAW,EAAQ,QAAQ,EACzC,MAAM,IAAI,EAAA,WAAW,mBAAoB,qCAAqC,EAGhF,IAAI,EAAS,GACT,EAA0B,GAAS,SAEvC,IAAK,IAAM,KAAS,EAAQ,CAG1B,GAFA,EAAA,YAAY,CAAK,EAEb,IAAa,IAAA,GACf,EAAW,EAAM,cACZ,GAAI,EAAM,WAAa,EAC5B,MAAM,IAAI,EAAA,sBAAsB,EAAS,KAAM,EAAM,SAAS,IAAI,EAGpE,GAAU,EAAM,MAClB,CAEA,GAAI,IAAa,IAAA,GAAW,MAAM,IAAI,EAAA,WAAW,gBAAiB,+CAA+C,EAEjH,OAAO,EAAA,YAAY,EAAQ,CAAQ,CACrC,CAIA,SAAgB,EAA6B,EAAiB,EAAwD,CAGpH,GAFA,EAAA,YAAY,CAAK,EAEb,OAAO,GAAmB,SAAU,OAAO,EAAe,EAAO,CAAc,EAEnF,GAAI,CAAC,MAAM,QAAQ,CAAc,EAC/B,MAAM,IAAI,EAAA,WAAW,qBAAsB,qCAAqC,EAElF,GAAI,EAAe,SAAW,EAAG,MAAM,IAAI,EAAA,WAAW,qBAAsB,oCAAoC,EAChH,GAAI,EAAe,OAAS,EAC1B,MAAM,IAAI,EAAA,WAAW,qBAAsB,4BAA4B,EAAqB,OAAO,EAErG,IAAK,IAAI,EAAQ,EAAG,EAAQ,EAAe,OAAQ,IACjD,GAAI,CAAC,OAAO,OAAO,EAAgB,CAAK,EACtC,MAAM,IAAI,EAAA,WAAW,qBAAsB,+CAA+C,EAI9F,IAAM,EAAU,EAAe,IAAI,EAAA,OAAO,EAE1C,GAAI,EAAQ,KAAM,GAAW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AClB,EAAY,EAAW,EAE7B,OAAO,MAAM,KAAK,CAAE,OAAQ,CAAW,GAAI,EAAG,IAC5C,EAAA,aAAa,GAAQ,OAAO,CAAK,EAAI,EAAY,GAAK,KAAO,EAAM,EAAM,QAAQ,CACnF,CACF"}
|
package/dist/aggregate.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"aggregate.d.ts","sourceRoot":"","sources":["../src/aggregate.ts"],"names":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"aggregate.d.ts","sourceRoot":"","sources":["../src/aggregate.ts"],"names":[],"mappings":"AAIA,OAAO,KAAK,EAAE,QAAQ,EAAE,KAAK,EAAE,MAAM,SAAS,CAAC;AAI/C,wBAAgB,GAAG,CAAC,CAAC,SAAS,QAAQ,EAAE,MAAM,EAAE,SAAS,KAAK,CAAC,CAAC,CAAC,EAAE,GAAG,KAAK,CAAC,CAAC,CAAC,CAAC;AAC/E,wBAAgB,GAAG,CAAC,CAAC,SAAS,QAAQ,EAAE,MAAM,EAAE,QAAQ,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,EAAE,OAAO,EAAE;IAAE,QAAQ,EAAE,CAAC,CAAA;CAAE,GAAG,KAAK,CAAC,CAAC,CAAC,CAAC;AA0BxG,wBAAgB,QAAQ,CAAC,CAAC,SAAS,QAAQ,EAAE,KAAK,EAAE,KAAK,CAAC,CAAC,CAAC,EAAE,KAAK,EAAE,MAAM,GAAG,KAAK,CAAC,CAAC,CAAC,EAAE,CAAC;AACzF,wBAAgB,QAAQ,CAAC,CAAC,SAAS,QAAQ,EAAE,KAAK,EAAE,KAAK,CAAC,CAAC,CAAC,EAAE,OAAO,EAAE,SAAS,MAAM,EAAE,GAAG,KAAK,CAAC,CAAC,CAAC,EAAE,CAAC"}
|
package/dist/aggregate.js
CHANGED
|
@@ -1,42 +1,46 @@
|
|
|
1
1
|
import { CoinsError as e, CurrencyMismatchError as t } from "./errors.js";
|
|
2
|
-
import { decimal as n, lcm as r } from "./
|
|
3
|
-
import {
|
|
2
|
+
import { decimal as n, lcm as r } from "./_decimal.js";
|
|
3
|
+
import { isCurrency as i } from "./currency.js";
|
|
4
|
+
import { assertMoney as a, createMoney as o } from "./money.js";
|
|
4
5
|
//#region src/aggregate.ts
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
6
|
+
var s = 1e5;
|
|
7
|
+
function c(n, r) {
|
|
8
|
+
if (r && !i(r.currency)) throw new e("INVALID_CURRENCY", "sum() requires a canonical currency");
|
|
9
|
+
let s = 0n, c = r?.currency;
|
|
10
|
+
for (let e of n) {
|
|
11
|
+
if (a(e), c === void 0) c = e.currency;
|
|
12
|
+
else if (e.currency !== c) throw new t(c.code, e.currency.code);
|
|
13
|
+
s += e.amount;
|
|
12
14
|
}
|
|
13
|
-
if (
|
|
14
|
-
return
|
|
15
|
+
if (c === void 0) throw new e("INVALID_MONEY", "sum() of empty iterable requires { currency }");
|
|
16
|
+
return o(s, c);
|
|
15
17
|
}
|
|
16
|
-
function
|
|
17
|
-
if (
|
|
18
|
-
if (
|
|
19
|
-
if (
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
let
|
|
23
|
-
if (
|
|
24
|
-
let
|
|
18
|
+
function l(t, i) {
|
|
19
|
+
if (a(t), typeof i == "number") return u(t, i);
|
|
20
|
+
if (!Array.isArray(i)) throw new e("INVALID_ALLOCATION", "Allocation weights must be an array");
|
|
21
|
+
if (i.length === 0) throw new e("INVALID_ALLOCATION", "Allocation weights cannot be empty");
|
|
22
|
+
if (i.length > s) throw new e("INVALID_ALLOCATION", `Allocation cannot exceed ${s} parts`);
|
|
23
|
+
for (let t = 0; t < i.length; t++) if (!Object.hasOwn(i, t)) throw new e("INVALID_ALLOCATION", "Allocation weights cannot contain empty slots");
|
|
24
|
+
let c = i.map(n);
|
|
25
|
+
if (c.some((e) => e.numerator < 0n)) throw new e("INVALID_ALLOCATION", "Allocation weights cannot be negative");
|
|
26
|
+
let l = c.reduce((e, t) => r(e, t.denominator), 1n), d = c.map((e) => e.numerator * (l / e.denominator)), f = d.reduce((e, t) => e + t, 0n);
|
|
27
|
+
if (f === 0n) throw new e("INVALID_ALLOCATION", "Allocation weights must include a positive value");
|
|
28
|
+
let p = t.amount < 0n ? -1n : 1n, m = t.amount < 0n ? -t.amount : t.amount, h = d.map((e) => m * e / f), g = m - h.reduce((e, t) => e + t, 0n), _ = d.map((e, t) => ({
|
|
25
29
|
index: t,
|
|
26
|
-
remainder:
|
|
30
|
+
remainder: m * e % f
|
|
27
31
|
})).sort((e, t) => e.remainder === t.remainder ? e.index - t.index : e.remainder > t.remainder ? -1 : 1);
|
|
28
|
-
for (let e of
|
|
29
|
-
if (
|
|
30
|
-
|
|
32
|
+
for (let e of _) {
|
|
33
|
+
if (g === 0n) break;
|
|
34
|
+
h[e.index] += 1n, g -= 1n;
|
|
31
35
|
}
|
|
32
|
-
return
|
|
36
|
+
return h.map((e) => o(e * p, t.currency));
|
|
33
37
|
}
|
|
34
|
-
function
|
|
35
|
-
if (!Number.
|
|
36
|
-
let r = BigInt(n), i = t.amount < 0n ? -1n : 1n,
|
|
37
|
-
return Array.from({ length: n }, (e, n) =>
|
|
38
|
+
function u(t, n) {
|
|
39
|
+
if (!Number.isSafeInteger(n) || n < 1 || n > s) throw new e("INVALID_ALLOCATION", `Allocation count must be a positive safe integer no greater than ${s}`);
|
|
40
|
+
let r = BigInt(n), i = t.amount < 0n ? -1n : 1n, a = t.amount < 0n ? -t.amount : t.amount, c = a / r, l = a % r;
|
|
41
|
+
return Array.from({ length: n }, (e, n) => o((c + (BigInt(n) < l ? 1n : 0n)) * i, t.currency));
|
|
38
42
|
}
|
|
39
43
|
//#endregion
|
|
40
|
-
export {
|
|
44
|
+
export { l as allocate, c as sum };
|
|
41
45
|
|
|
42
46
|
//# sourceMappingURL=aggregate.js.map
|
package/dist/aggregate.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"aggregate.js","names":[],"sources":["../src/aggregate.ts"],"sourcesContent":["import { decimal, lcm } from './
|
|
1
|
+
{"version":3,"file":"aggregate.js","names":[],"sources":["../src/aggregate.ts"],"sourcesContent":["import { decimal, lcm } from './_decimal';\nimport { isCurrency } from './currency';\nimport { CoinsError, CurrencyMismatchError } from './errors';\nimport { assertMoney, createMoney } from './money';\nimport type { Currency, Money } from './types';\n\nconst MAX_ALLOCATION_PARTS = 100_000;\n\nexport function sum<C extends Currency>(values: readonly Money<C>[]): Money<C>;\nexport function sum<C extends Currency>(values: Iterable<Money<C>>, options: { currency: C }): Money<C>;\nexport function sum<C extends Currency>(values: Iterable<Money<C>>, options?: { currency: C }): Money<C> {\n if (options && !isCurrency(options.currency)) {\n throw new CoinsError('INVALID_CURRENCY', 'sum() requires a canonical currency');\n }\n\n let amount = 0n;\n let currency: C | undefined = options?.currency;\n\n for (const value of values) {\n assertMoney(value);\n\n if (currency === undefined) {\n currency = value.currency;\n } else if (value.currency !== currency) {\n throw new CurrencyMismatchError(currency.code, value.currency.code);\n }\n\n amount += value.amount;\n }\n\n if (currency === undefined) throw new CoinsError('INVALID_MONEY', 'sum() of empty iterable requires { currency }');\n\n return createMoney(amount, currency);\n}\n\nexport function allocate<C extends Currency>(value: Money<C>, count: number): Money<C>[];\nexport function allocate<C extends Currency>(value: Money<C>, weights: readonly string[]): Money<C>[];\nexport function allocate<C extends Currency>(value: Money<C>, weightsOrCount: number | readonly string[]): Money<C>[] {\n assertMoney(value);\n\n if (typeof weightsOrCount === 'number') return allocateEvenly(value, weightsOrCount);\n\n if (!Array.isArray(weightsOrCount)) {\n throw new CoinsError('INVALID_ALLOCATION', 'Allocation weights must be an array');\n }\n if (weightsOrCount.length === 0) throw new CoinsError('INVALID_ALLOCATION', 'Allocation weights cannot be empty');\n if (weightsOrCount.length > MAX_ALLOCATION_PARTS) {\n throw new CoinsError('INVALID_ALLOCATION', `Allocation cannot exceed ${MAX_ALLOCATION_PARTS} parts`);\n }\n for (let index = 0; index < weightsOrCount.length; index++) {\n if (!Object.hasOwn(weightsOrCount, index)) {\n throw new CoinsError('INVALID_ALLOCATION', 'Allocation weights cannot contain empty slots');\n }\n }\n\n const weights = weightsOrCount.map(decimal);\n\n if (weights.some((weight) => weight.numerator < 0n)) {\n throw new CoinsError('INVALID_ALLOCATION', 'Allocation weights cannot be negative');\n }\n\n const commonDenominator = weights.reduce((result, weight) => lcm(result, weight.denominator), 1n);\n const scaledWeights = weights.map((weight) => weight.numerator * (commonDenominator / weight.denominator));\n const totalWeight = scaledWeights.reduce((result, weight) => result + weight, 0n);\n\n if (totalWeight === 0n)\n throw new CoinsError('INVALID_ALLOCATION', 'Allocation weights must include a positive value');\n\n const sign = value.amount < 0n ? -1n : 1n;\n const absolute = value.amount < 0n ? -value.amount : value.amount;\n const shares = scaledWeights.map((weight) => (absolute * weight) / totalWeight);\n let remainder = absolute - shares.reduce((result, amount) => result + amount, 0n);\n const ranked = scaledWeights\n .map((weight, index) => ({ index, remainder: (absolute * weight) % totalWeight }))\n .sort((left, right) =>\n left.remainder === right.remainder ? left.index - right.index : left.remainder > right.remainder ? -1 : 1,\n );\n\n for (const entry of ranked) {\n if (remainder === 0n) break;\n\n shares[entry.index]! += 1n;\n remainder -= 1n;\n }\n\n return shares.map((amount) => createMoney(amount * sign, value.currency));\n}\n\nfunction allocateEvenly<C extends Currency>(value: Money<C>, countValue: number): Money<C>[] {\n if (!Number.isSafeInteger(countValue) || countValue < 1 || countValue > MAX_ALLOCATION_PARTS) {\n throw new CoinsError(\n 'INVALID_ALLOCATION',\n `Allocation count must be a positive safe integer no greater than ${MAX_ALLOCATION_PARTS}`,\n );\n }\n\n const count = BigInt(countValue);\n const sign = value.amount < 0n ? -1n : 1n;\n const absolute = value.amount < 0n ? -value.amount : value.amount;\n const base = absolute / count;\n const remainder = absolute % count;\n\n return Array.from({ length: countValue }, (_, index) =>\n createMoney((base + (BigInt(index) < remainder ? 1n : 0n)) * s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@@
|
|
|
1
|
-
Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});var e=class extends Error{code;constructor(e,t,n){super(t,n),this.code=e,this.name=new.target.name,Object.setPrototypeOf(this,new.target.prototype)}},t=class extends e{expected;received;constructor(e,t){super(`CURRENCY_MISMATCH`,`Currency mismatch: ${e} and ${t}`),this.expected=e,this.received=t}},n=class extends e{value;constructor(e){super(`INVALID_CURRENCY`,`Unsupported currency: "${String(e)}"`),this.value=e}},r=/^(-?)(\d+)(?:\.(\d+))?$/,i=1e3,a=100;function o(t){if(t.length>i)throw new e(`INVALID_DECIMAL`,`Decimal input is too long`);let n=r.exec(t);if(!n)throw new e(`INVALID_DECIMAL`,`Invalid decimal: "${t}"`);let o=(n[3]??``).replace(/0+$/,``);if(o.length>a)throw new e(`INVALID_DECIMAL`,`Decimal precision cannot exceed ${a} places`);let s=10n**BigInt(o.length),c=BigInt(n[2])*s+BigInt(o||`0`),u=n[1]===`-`&&c!==0n?-c:c,d=l(u<0n?-u:u,s);return Object.freeze({denominator:s/d,numerator:u/d})}function s(t,n,r){if(n<=0n)throw new e(`INVALID_DECIMAL`,`Decimal denominator must be positive`);let i=t<0n,a=i?-t:t,o=a/n,s=a%n;if(s===0n)return i?-o:o;let c=(()=>{switch(r){case`awayFromZero`:return!0;case`ceil`:return!i;case`floor`:return i;case`halfAwayFromZero`:return s*2n>=n;case`halfEven`:{let e=s*2n;return e>n||e===n&&o%2n!=0n}case`towardZero`:return!1}})()?o+1n:o;return i?-c:c}function c(e,t){let n=e<0n,r=n?-e:e,i=10n**BigInt(t),a=r/i;if(t===0)return`${n?`-`:``}${a}`;let o=(r%i).toString().padStart(t,`0`);return`${n?`-`:``}${a}.${o}`}function l(e,t){let n=e,r=t;for(;r!==0n;)[n,r]=[r,n%r];return n===0n?1n:n}function u(e,t){return e/l(e,t)*t}var d=new Map,f=new Map;function p(e,t){let n=w(e,t);return d.set(e,n),n}var m=p(`USD`,2),h=p(`EUR`,2),g=p(`GBP`,2),_=p(`JPY`,0),v=p(`KRW`,0),y=p(`BHD`,3),ee=p(`KWD`,3);function b({code:e,minorUnit:t}){T(e,t);let n=d.get(e);if(n){if(n.minorUnit!==t)throw E(e,n.minorUnit);return n}let r=f.get(e);if(r){if(r.minorUnit!==t)throw E(e,r.minorUnit);return r}let i=w(e,t);return f.set(e,i),i}function x(e){let t=d.get(e)??f.get(e);if(!t)throw new n(e);return t}function S(e){if(typeof e!=`object`||!e)return!1;let t=e;return typeof t.code==`string`&&(d.get(t.code)===e||f.get(t.code)===e)}function C(e){let t=d.get(e);if(!t)throw new n(e);return t}function w(e,t){return T(e,t),Object.freeze({code:e,minorUnit:t})}function T(t,n){if(!/^[A-Z]{3}$/.test(t))throw new e(`INVALID_CURRENCY`,`Currency code must be three uppercase letters: "${t}"`);if(!Number.isInteger(n)||n<0||n>6)throw new e(`INVALID_CURRENCY`,`Currency "${t}" must have 0–6 minor-unit digits`)}function E(t,n){return new e(`INVALID_CURRENCY`,`Currency "${t}" already has ${n} minor-unit digits`)}var D=`halfAwayFromZero`;function O(t,n,r){if(B(n),typeof t==`bigint`){if(!r||!(`unit`in r)||r.unit!==`minor`)throw new e(`INVALID_MONEY`,`Bigint amounts require { unit: 'minor' }`);return L(t,n)}if(r&&`unit`in r)throw new e(`INVALID_MONEY`,`Decimal strings do not accept a unit option`);let i=o(t),a=i.numerator*10n**BigInt(n.minorUnit);if(a%i.denominator!==0n&&!r)throw new e(`INVALID_MONEY`,`Amount "${t}" exceeds ${n.code} precision; provide rounding`);return L(s(a,i.denominator,r?.rounding??D),n)}function k(t){if(!V(t))throw new e(`INVALID_MONEY`,`Money must be a plain data object`);let n=Object.getOwnPropertyDescriptors(t),r=n.amount,i=n.currency;if(!H(r)||!H(i))throw new e(`INVALID_MONEY`,`Money properties must be plain data values`);if(typeof r.value!=`bigint`||!S(i.value))throw new e(`INVALID_MONEY`,`Money must contain bigint amount and a registered currency`);return L(r.value,i.value)}function A(e){try{return k(e),!0}catch{return!1}}function j(e,t){return z(e,t),L(e.amount+t.amount,e.currency)}function te(e,t){return z(e,t),L(e.amount-t.amount,e.currency)}function ne(e,t,n={}){R(e);let r=o(t);return L(s(e.amount*r.numerator,r.denominator,n.rounding??D),e.currency)}function re(t,n,r={}){R(t);let i=o(n);if(i.numerator===0n)throw new e(`DIVISION_BY_ZERO`,`Cannot divide money by zero`);let a=i.numerator<0n,c=a?-i.numerator:i.numerator,l=s(t.amount*i.denominator,c,r.rounding??D);return L(a?-l:l,t.currency)}function M(e,t){return z(e,t),e.amount===t.amount?0:e.amount<t.amount?-1:1}function ie(t,n){if(M(n.min,n.max)===1)throw new e(`INVALID_MONEY`,`Clamp minimum cannot exceed maximum`);return M(t,n.min)===-1?n.min:M(t,n.max)===1?n.max:t}function ae(e){return R(e),L(e.amount<0n?-e.amount:e.amount,e.currency)}function N(e){return R(e),L(-e.amount,e.currency)}function P(t,n){R(t);let{fractionDigits:r,rounding:i=D}=n;if(!Number.isInteger(r)||r<0||r>t.currency.minorUnit)throw new e(`INVALID_ROUNDING`,`fractionDigits must be an integer from 0 to ${t.currency.minorUnit}`);let a=10n**BigInt(t.currency.minorUnit-r);return L(s(t.amount,a,i)*a,t.currency)}function F(e){return R(e),c(e.amount,e.currency.minorUnit)}function I(e,t){return B(t),L(e,t)}function L(e,t){return Object.freeze({amount:e,currency:t})}function R(t){if(!Object.isFrozen(t)||!S(t.currency))throw new e(`INVALID_MONEY`,`Money must be a canonical Coins value`)}function z(e,n){if(R(e),R(n),e.currency!==n.currency)throw new t(e.currency.code,n.currency.code)}function B(t){if(!S(t))throw new e(`INVALID_CURRENCY`,`Money requires a registered currency`)}function V(e){if(typeof e!=`object`||!e)return!1;let t=Object.getPrototypeOf(e);return t===Object.prototype||t===null}function H(e){return e!==void 0&&`value`in e&&e.get===void 0&&e.set===void 0}function U(n,r){let i=0n,a=r?.currency;for(let r of n){if(!A(r))throw new e(`INVALID_MONEY`,`sum() requires canonical money values`);if(a===void 0)a=r.currency;else if(r.currency!==a)throw new t(a.code,r.currency.code);i+=r.amount}if(a===void 0)throw new e(`INVALID_MONEY`,`sum() of empty iterable requires { currency }`);return I(i,a)}function W(t,n){if(!A(t))throw new e(`INVALID_MONEY`,`allocate() requires canonical money`);if(typeof n==`number`)return G(t,n);if(n.length===0)throw new e(`INVALID_ALLOCATION`,`Allocation weights cannot be empty`);let r=n.map(o);if(r.some(e=>e.numerator<0n))throw new e(`INVALID_ALLOCATION`,`Allocation weights cannot be negative`);let i=r.reduce((e,t)=>u(e,t.denominator),1n),a=r.map(e=>e.numerator*(i/e.denominator)),s=a.reduce((e,t)=>e+t,0n);if(s===0n)throw new e(`INVALID_ALLOCATION`,`Allocation weights must include a positive value`);let c=t.amount<0n?-1n:1n,l=t.amount<0n?-t.amount:t.amount,d=a.map(e=>l*e/s),f=l-d.reduce((e,t)=>e+t,0n),p=a.map((e,t)=>({index:t,remainder:l*e%s})).sort((e,t)=>e.remainder===t.remainder?e.index-t.index:e.remainder>t.remainder?-1:1);for(let e of p){if(f===0n)break;d[e.index]+=1n,f-=1n}return d.map(e=>I(e*c,t.currency))}function G(t,n){if(!Number.isInteger(n)||n<1)throw new e(`INVALID_ALLOCATION`,`Allocation count must be a positive integer`);let r=BigInt(n),i=t.amount<0n?-1n:1n,a=t.amount<0n?-t.amount:t.amount,o=a/r,s=a%r;return Array.from({length:n},(e,n)=>I((o+(BigInt(n)<s?1n:0n))*i,t.currency))}function K({from:t,to:n,value:r}){if(!S(t)||!S(n))throw new e(`INVALID_CURRENCY`,`Exchange rate requires registered currencies`);let i=o(r);if(i.numerator<0n)throw new e(`INVALID_DECIMAL`,`Exchange rates cannot be negative`);return Object.freeze({from:t,to:n,value:i})}function q(n,r,i={}){if(!A(n)||!oe(r))throw new e(`INVALID_MONEY`,`Exchange requires canonical money and rate values`);if(n.currency!==r.from)throw new t(n.currency.code,r.from.code);return I(s(n.amount*r.value.numerator*10n**BigInt(r.to.minorUnit),r.value.denominator*10n**BigInt(r.from.minorUnit),i.rounding??`halfAwayFromZero`),r.to)}function oe(e){if(typeof e!=`object`||!e||!Object.isFrozen(e))return!1;let t=e;return S(t.from)&&S(t.to)&&typeof t.value==`object`&&t.value!==null&&Object.isFrozen(t.value)&&typeof t.value.numerator==`bigint`&&t.value.numerator>=0n&&typeof t.value.denominator==`bigint`&&t.value.denominator>0n}var J=20,se=`halfAwayFromZero`,Y=new Map,X=new Map;function ce(e,t={}){return Z(e,t).map(e=>e.value).join(``)}function Z(t,n={}){if(!A(t))throw new e(`INVALID_MONEY`,`format() requires canonical money`);let{locale:r=`en-US`,maximumFractionDigits:i=t.currency.minorUnit,minimumFractionDigits:a=t.currency.minorUnit,rounding:o=se,style:c=`symbol`}=n;le(a,i);let l=10n**BigInt(i),u=i>=t.currency.minorUnit?t.amount*10n**BigInt(i-t.currency.minorUnit):s(t.amount,10n**BigInt(t.currency.minorUnit-i),o),d=u<0n,f=d?-u:u,p=f/l,m=(i===0?``:(f%l).toString().padStart(i,`0`)).replace(RegExp(`0{0,${Math.max(0,i-a)}}$`),``),h=ue(r,t.currency.code,c,d),g=[],_=!1;for(let e of h)e.type!==`group`&&(e.type===`integer`?_||=(g.push({type:`integer`,value:Q(r).format(p)}),!0):e.type===`decimal`?m&&g.push({type:`decimal`,value:e.value}):e.type===`fraction`?m&&g.push({type:`fraction`,value:m}):e.type===`currency`||e.type===`minusSign`||e.type===`plusSign`?g.push({type:e.type,value:e.value}):g.push({type:`literal`,value:e.value}));return g}function le(t,n){if(!Number.isInteger(n)||!Number.isInteger(t)||t<0||n<t||n>J)throw new e(`FORMAT_ERROR`,`Fraction digits must be integers satisfying 0 ≤ minimum ≤ maximum ≤ ${J}`)}function ue(t,n,r,i){let a=`${t}\0${n}\0${r}\0${i}`,o=X.get(a);if(o)return o;try{let e=new Intl.NumberFormat(t,{currency:n,currencyDisplay:r,maximumFractionDigits:1,minimumFractionDigits:1,style:`currency`}).formatToParts(i?-1.1:1.1);return X.set(a,e),e}catch(r){throw new e(`FORMAT_ERROR`,`Cannot format currency "${n}" for locale "${t}"`,{cause:r})}}function Q(t){let n=Y.get(t);if(n)return n;try{let e=new Intl.NumberFormat(t,{maximumFractionDigits:0,useGrouping:!0});return Y.set(t,e),e}catch(n){throw new e(`FORMAT_ERROR`,`Cannot create number formatter for locale "${t}"`,{cause:n})}}var de=/^(?:0|-[1-9]\d*|[1-9]\d*)$/,$=[`amount`,`currency`,`unit`];function fe(e){return{amount:e.amount.toString(),currency:e.currency.code,unit:`minor`}}function pe(t,n={}){try{let e=me(t),r=n.currency??C;return O(BigInt(e.amount),r(e.currency),{unit:`minor`})}catch(t){throw new e(`INVALID_MONEY`,`Invalid Money JSON`,{cause:t})}}function me(e){if(typeof e!=`object`||!e||Object.getPrototypeOf(e)!==Object.prototype)throw TypeError(`Money JSON must be a plain object`);let t=Object.getOwnPropertyDescriptors(e),n=Reflect.ownKeys(e);if(n.length!==$.length||!$.every(e=>n.includes(e)))throw TypeError(`Money JSON must contain only amount, currency, and unit`);for(let e of $){let n=t[e];if(!n||!(`value`in n)||n.get||n.set)throw TypeError(`Money JSON property "${e}" must be a data value`)}let r=t.amount?.value,i=t.currency?.value,a=t.unit?.value;if(typeof r!=`string`||!de.test(r))throw TypeError(`Money JSON amount must be a canonical integer string`);if(typeof i!=`string`||a!==`minor`)throw TypeError(`Money JSON currency/unit are invalid`);return{amount:r,currency:i,unit:a}}exports.BHD=y,exports.CoinsError=e,exports.CurrencyMismatchError=t,exports.EUR=h,exports.GBP=g,exports.InvalidCurrencyError=n,exports.JPY=_,exports.KRW=v,exports.KWD=ee,exports.USD=m,exports.abs=ae,exports.add=j,exports.allocate=W,exports.clamp=ie,exports.compare=M,exports.currency=x,exports.defineCurrency=b,exports.divide=re,exports.exchange=q,exports.exchangeRate=K,exports.format=ce,exports.formatParts=Z,exports.isCurrency=S,exports.isMoney=A,exports.money=O,exports.multiply=ne,exports.negate=N,exports.parseMoney=k,exports.parseMoneyJSON=pe,exports.round=P,exports.subtract=te,exports.sum=U,exports.toDecimal=F,exports.toJSON=fe;
|
|
1
|
+
Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});var e=class extends Error{static errorName=`CoinsError`;code;constructor(e,t,n){super(t,n),this.code=e,this.name=new.target.errorName,Object.setPrototypeOf(this,new.target.prototype)}},t=class extends e{static errorName=`CurrencyMismatchError`;expected;received;constructor(e,t){super(`CURRENCY_MISMATCH`,`Currency mismatch: canonical ${e} and ${t} definitions differ`),this.expected=e,this.received=t}};function n(e){try{return String(e)}catch{return`<unprintable>`}}var r=class extends e{static errorName=`InvalidCurrencyError`;value;constructor(e){super(`INVALID_CURRENCY`,`Unsupported currency: "${n(e)}"`),this.value=e}},i=/^(-?)(\d+)(?:\.(\d+))?$/,a=1e3,o=100,s=new Set([`awayFromZero`,`ceil`,`floor`,`halfAwayFromZero`,`halfEven`,`towardZero`]);function c(t){if(!s.has(t))throw new e(`INVALID_ROUNDING`,`Unknown rounding mode: ${String(t)}`)}function l(t){if(typeof t!=`string`)throw new e(`INVALID_DECIMAL`,`Decimal input must be a string`);if(t.length>a)throw new e(`INVALID_DECIMAL`,`Decimal input is too long`);let n=i.exec(t);if(!n)throw new e(`INVALID_DECIMAL`,`Invalid decimal: "${t}"`);let r=(n[3]??``).replace(/0+$/,``);if(r.length>o)throw new e(`INVALID_DECIMAL`,`Decimal precision cannot exceed ${o} places`);let s=10n**BigInt(r.length),c=BigInt(n[2])*s+BigInt(r||`0`),l=n[1]===`-`&&c!==0n?-c:c,u=f(l<0n?-l:l,s);return Object.freeze({denominator:s/u,numerator:l/u})}function u(t,n,r){if(c(r),n<=0n)throw new e(`INVALID_DECIMAL`,`Decimal denominator must be positive`);let i=t<0n,a=i?-t:t,o=a/n,s=a%n;if(s===0n)return i?-o:o;let l=(()=>{switch(r){case`awayFromZero`:return!0;case`ceil`:return!i;case`floor`:return i;case`halfAwayFromZero`:return s*2n>=n;case`halfEven`:{let e=s*2n;return e>n||e===n&&o%2n!=0n}case`towardZero`:return!1;default:throw new e(`INVALID_ROUNDING`,`Unknown rounding mode: ${r}`)}})()?o+1n:o;return i?-l:l}function d(e,t){let n=e<0n,r=n?-e:e,i=10n**BigInt(t),a=r/i;if(t===0)return`${n?`-`:``}${a}`;let o=(r%i).toString().padStart(t,`0`);return`${n?`-`:``}${a}.${o}`}function f(e,t){let n=e,r=t;for(;r!==0n;)[n,r]=[r,n%r];return n===0n?1n:n}function p(e,t){return e/f(e,t)*t}var m=new Map,h=new WeakSet;function g(e,t){te(e,t);let n=Object.freeze({code:e,minorUnit:t});return h.add(n),n}function _(e,t){let n=g(e,t);return m.set(e,n),n}var v=_(`USD`,2),y=_(`EUR`,2),b=_(`GBP`,2),x=_(`JPY`,0),ee=_(`KRW`,0),S=_(`BHD`,3),C=_(`KWD`,3);function w(t){if(typeof t==`string`){let e=m.get(t);if(!e)throw new r(t);return e}if(typeof t!=`object`||!t)throw new e(`INVALID_CURRENCY`,`Currency definition must be an object`);return g(t.code,t.minorUnit)}function T(e){return typeof e==`object`&&!!e&&h.has(e)}function te(t,n){if(!/^[A-Z]{3}$/.test(t))throw new e(`INVALID_CURRENCY`,`Currency code must be three uppercase letters: "${t}"`);if(!Number.isInteger(n)||n<0||n>6)throw new e(`INVALID_CURRENCY`,`Currency "${t}" must have 0–6 minor-unit digits`)}var E=new WeakSet,D=`halfAwayFromZero`,O=/^(?:0|-[1-9]\d*|[1-9]\d*)$/,k=1e3;function A(t,n,r){if(H(n),typeof t==`bigint`){if(!r||!(`unit`in r)||r.unit!==`minor`)throw new e(`INVALID_MONEY`,`Bigint amounts require { unit: 'minor' }`);return z(t,n)}if(r&&`unit`in r)throw new e(`INVALID_MONEY`,`Decimal strings do not accept a unit option`);let i=l(t),a=i.numerator*10n**BigInt(n.minorUnit);if(a%i.denominator!==0n&&r?.rounding===void 0)throw new e(`INVALID_MONEY`,`Amount "${t}" exceeds ${n.code} precision; provide rounding`);return z(u(a,i.denominator,r?.rounding??D),n)}function j(t,n){if(!U(t))throw new e(`INVALID_MONEY`,`Money must be a plain data object`);let r=Object.getOwnPropertyDescriptors(t),i=r.amount,a=r.currency;if(!W(i)||!W(a))throw new e(`INVALID_MONEY`,`Money properties must be plain data values`);let o=Reflect.ownKeys(t);if(typeof i.value==`bigint`&&T(a.value)){if(o.length!==2)throw new e(`INVALID_MONEY`,`Plain money must have exactly the keys amount and currency`);return z(i.value,a.value)}let s=r.unit;if(typeof i.value==`string`&&typeof a.value==`string`&&W(s)&&s.value===`minor`){if(o.length!==3)throw new e(`INVALID_MONEY`,`MoneyJSON must have exactly the keys amount, currency, unit`);if(i.value.length>k)throw new e(`INVALID_MONEY`,`Money JSON amount is too long; maximum ${k} characters`);if(!O.test(i.value))throw new e(`INVALID_MONEY`,`Invalid Money JSON amount "${i.value}"`);let t=n?.currency??w;try{let n=t(a.value);if(!T(n)||n.code!==a.value)throw new e(`INVALID_CURRENCY`,`Currency resolver must return the canonical "${a.value}" definition`);return A(BigInt(i.value),n,{unit:`minor`})}catch(t){throw new e(`INVALID_MONEY`,`Invalid Money JSON for currency "${a.value}"`,{cause:t})}}throw new e(`INVALID_MONEY`,`Money must contain bigint amount and a registered currency, or a valid MoneyJSON shape`)}function M(e){return typeof e==`object`&&!!e&&E.has(e)}function ne(e,t){return V(e,t),z(e.amount+t.amount,e.currency)}function re(e,t){return V(e,t),z(e.amount-t.amount,e.currency)}function ie(e,t,n={}){B(e);let r=l(t);return z(u(e.amount*r.numerator,r.denominator,n.rounding??D),e.currency)}function ae(t,n,r={}){B(t);let i=l(n);if(i.numerator===0n)throw new e(`DIVISION_BY_ZERO`,`Cannot divide money by zero`);let a=i.numerator<0n?-i.numerator:i.numerator,o=t.amount*i.denominator;return z(u(i.numerator<0n?-o:o,a,r.rounding??D),t.currency)}function N(e,t){return V(e,t),e.amount===t.amount?0:e.amount<t.amount?-1:1}function P(t,n){if(N(n.min,n.max)===1)throw new e(`INVALID_RANGE`,`Clamp minimum cannot exceed maximum`);return N(t,n.min)===-1?n.min:N(t,n.max)===1?n.max:t}function F(e){return B(e),z(e.amount<0n?-e.amount:e.amount,e.currency)}function I(e){return B(e),z(-e.amount,e.currency)}function L(t,n){B(t);let{fractionDigits:r,rounding:i=D}=n;if(!Number.isInteger(r)||r<0||r>t.currency.minorUnit)throw new e(`INVALID_ROUNDING`,`fractionDigits must be an integer from 0 to ${t.currency.minorUnit}`);let a=10n**BigInt(t.currency.minorUnit-r);return z(u(t.amount,a,i)*a,t.currency)}function R(e){return B(e),d(e.amount,e.currency.minorUnit)}function z(e,t){let n=Object.freeze({amount:e,currency:t});return E.add(n),n}function B(t){if(!M(t))throw new e(`INVALID_MONEY`,`Money must be a canonical @vielzeug/coins value`)}function V(e,n){if(B(e),B(n),e.currency!==n.currency)throw new t(e.currency.code,n.currency.code)}function H(t){if(!T(t))throw new e(`INVALID_CURRENCY`,`Money requires a registered currency`)}function U(e){if(typeof e!=`object`||!e)return!1;let t=Object.getPrototypeOf(e);return t===Object.prototype||t===null}function W(e){return e!==void 0&&`value`in e&&e.get===void 0&&e.set===void 0}var G=1e5;function K(n,r){if(r&&!T(r.currency))throw new e(`INVALID_CURRENCY`,`sum() requires a canonical currency`);let i=0n,a=r?.currency;for(let e of n){if(B(e),a===void 0)a=e.currency;else if(e.currency!==a)throw new t(a.code,e.currency.code);i+=e.amount}if(a===void 0)throw new e(`INVALID_MONEY`,`sum() of empty iterable requires { currency }`);return z(i,a)}function q(t,n){if(B(t),typeof n==`number`)return oe(t,n);if(!Array.isArray(n))throw new e(`INVALID_ALLOCATION`,`Allocation weights must be an array`);if(n.length===0)throw new e(`INVALID_ALLOCATION`,`Allocation weights cannot be empty`);if(n.length>G)throw new e(`INVALID_ALLOCATION`,`Allocation cannot exceed ${G} parts`);for(let t=0;t<n.length;t++)if(!Object.hasOwn(n,t))throw new e(`INVALID_ALLOCATION`,`Allocation weights cannot contain empty slots`);let r=n.map(l);if(r.some(e=>e.numerator<0n))throw new e(`INVALID_ALLOCATION`,`Allocation weights cannot be negative`);let i=r.reduce((e,t)=>p(e,t.denominator),1n),a=r.map(e=>e.numerator*(i/e.denominator)),o=a.reduce((e,t)=>e+t,0n);if(o===0n)throw new e(`INVALID_ALLOCATION`,`Allocation weights must include a positive value`);let s=t.amount<0n?-1n:1n,c=t.amount<0n?-t.amount:t.amount,u=a.map(e=>c*e/o),d=c-u.reduce((e,t)=>e+t,0n),f=a.map((e,t)=>({index:t,remainder:c*e%o})).sort((e,t)=>e.remainder===t.remainder?e.index-t.index:e.remainder>t.remainder?-1:1);for(let e of f){if(d===0n)break;u[e.index]+=1n,d-=1n}return u.map(e=>z(e*s,t.currency))}function oe(t,n){if(!Number.isSafeInteger(n)||n<1||n>G)throw new e(`INVALID_ALLOCATION`,`Allocation count must be a positive safe integer no greater than ${G}`);let r=BigInt(n),i=t.amount<0n?-1n:1n,a=t.amount<0n?-t.amount:t.amount,o=a/r,s=a%r;return Array.from({length:n},(e,n)=>z((o+(BigInt(n)<s?1n:0n))*i,t.currency))}var J=new WeakSet;function se({from:t,to:n,value:r}){if(!T(t)||!T(n))throw new e(`INVALID_CURRENCY`,`Exchange rate requires registered currencies`);let i=l(r);if(i.numerator<=0n)throw new e(`INVALID_DECIMAL`,`Exchange rates must be positive`);let a=Object.freeze({from:t,to:n,value:i});return J.add(a),a}function Y(e){return typeof e==`object`&&!!e&&J.has(e)}function ce(n,r,i={}){if(B(n),!Y(r))throw new e(`INVALID_EXCHANGE_RATE`,`Exchange requires a canonical exchange rate`);if(n.currency!==r.from)throw new t(n.currency.code,r.from.code);return z(u(n.amount*r.value.numerator*10n**BigInt(r.to.minorUnit),r.value.denominator*10n**BigInt(r.from.minorUnit),i.rounding??`halfAwayFromZero`),r.to)}var X=20,Z=`halfAwayFromZero`,le={awayFromZero:`expand`,ceil:`ceil`,floor:`floor`,halfAwayFromZero:`halfExpand`,halfEven:`halfEven`,towardZero:`trunc`};function ue(e,t={}){return Q(e,t).map(e=>e.value).join(``)}function Q(t,n={}){B(t),c(n.rounding??Z);let{maximum:r,minimum:i}=de(t.currency.minorUnit,n),a=n.style??`symbol`;try{return fe(new Intl.NumberFormat(n.locale??`en-US`,{currency:t.currency.code,currencyDisplay:a,maximumFractionDigits:r,minimumFractionDigits:i,roundingMode:le[n.rounding??Z],style:`currency`,useGrouping:!0}).formatToParts(R(t)))}catch(r){throw r instanceof e?r:new e(`FORMAT_ERROR`,`Cannot format currency "${t.currency.code}" for locale "${n.locale??`en-US`}"`,{cause:r})}}function de(t,n){let r=n.maximumFractionDigits,i=n.minimumFractionDigits;$(`maximumFractionDigits`,r),$(`minimumFractionDigits`,i);let a=r??Math.max(t,i??t),o=i??Math.min(t,r??t);if(o>a)throw new e(`FORMAT_ERROR`,`minimumFractionDigits cannot exceed maximumFractionDigits`);return{maximum:a,minimum:o}}function $(t,n){if(n!==void 0&&(!Number.isInteger(n)||n<0||n>X))throw new e(`FORMAT_ERROR`,`Fraction digits must be integers satisfying 0 ≤ minimum ≤ maximum ≤ ${X} (${t})`)}function fe(e){let t=[];for(let n of e)if(n.type===`integer`||n.type===`group`){let e=t.at(-1);e?.type===`integer`?t[t.length-1]={type:`integer`,value:e.value+n.value}:t.push({type:`integer`,value:n.value})}else n.type===`currency`||n.type===`decimal`||n.type===`fraction`||n.type===`literal`||n.type===`minusSign`||n.type===`plusSign`?t.push({type:n.type,value:n.value}):t.push({type:`literal`,value:n.value});return t}function pe(e){return B(e),{amount:e.amount.toString(),currency:e.currency.code,unit:`minor`}}exports.BHD=S,exports.CoinsError=e,exports.CurrencyMismatchError=t,exports.EUR=y,exports.GBP=b,exports.InvalidCurrencyError=r,exports.JPY=x,exports.KRW=ee,exports.KWD=C,exports.USD=v,exports.abs=F,exports.add=ne,exports.allocate=q,exports.clamp=P,exports.compare=N,exports.currency=w,exports.decodeMoney=j,exports.divide=ae,exports.exchange=ce,exports.exchangeRate=se,exports.format=ue,exports.formatParts=Q,exports.isCurrency=T,exports.isExchangeRate=Y,exports.isMoney=M,exports.money=A,exports.multiply=ie,exports.negate=I,exports.round=L,exports.subtract=re,exports.sum=K,exports.toDecimal=R,exports.toJSON=pe;
|
|
2
2
|
//# sourceMappingURL=coins.cjs.map
|