@pyreon/money 0.0.0-stage → 0.53.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.
@@ -0,0 +1 @@
1
+ {"version":3,"file":"money-B9MhDL2i.js","names":[],"sources":["../../src/currency.ts","../../src/money.ts"],"sourcesContent":["import { badRange, badValue, show } from './errors'\n\n/** An ISO 4217 code (`\"EUR\"`) or a code registered with `defineCurrency`. */\nexport type CurrencyCode = string\n\n/** The most currencies `defineCurrency` registers, and the most digit counts `currencyDigits` remembers. */\nconst LIMIT = 64\nconst registry = new Map<string, number>()\nconst platform = new Map<string, number>()\nlet iso: Set<string> | null | undefined\n\nfunction isoCodes(): Set<string> | null {\n if (iso === undefined) {\n const list = (Intl as { supportedValuesOf?: (key: string) => string[] }).supportedValuesOf?.('currency')\n\n iso = list === undefined ? null : new Set(list)\n }\n\n return iso\n}\n\nfunction wellFormed(code: string): boolean {\n return code.length === 3 && code.charCodeAt(0) - 65 >>> 0 < 26 && code.charCodeAt(1) - 65 >>> 0 < 26 && code.charCodeAt(2) - 65 >>> 0 < 26\n}\n\n/** The fraction digits `Intl` uses for an ISO code, remembered for `LIMIT` codes (the oldest is dropped first). */\nfunction platformDigits(code: string): number | undefined {\n const hit = platform.get(code)\n\n if (hit !== undefined) return hit\n if (!wellFormed(code)) return undefined\n const known = isoCodes()\n\n if (known !== null && !known.has(code)) return undefined\n const digits = new Intl.NumberFormat('en', { style: 'currency', currency: code }).resolvedOptions().maximumFractionDigits ?? 2\n\n if (platform.size >= LIMIT) platform.delete(platform.keys().next().value as string)\n platform.set(code, digits)\n\n return digits\n}\n\n/** The digits of a code for a calling function: a registered code, else the platform's, else a `[Pyreon]` error. */\nexport function digitsOf(fn: string, code: unknown): number {\n const digits = typeof code === 'string' ? (registry.get(code) ?? platformDigits(code)) : undefined\n\n return digits ?? unknownCurrency(fn, code)\n}\n\nfunction unknownCurrency(fn: string, code: unknown): never {\n const lower = typeof code === 'string' && wellFormed(code.toUpperCase()) && code !== code.toUpperCase()\n const fix = lower\n ? `Currency codes are upper case: use ${JSON.stringify((code as string).toUpperCase())}.`\n : 'Use an ISO 4217 code such as \"EUR\", or register your own with defineCurrency(\"PTS\", { digits: 0 }).'\n\n return badValue(fn, 'a known currency code', code, fix)\n}\n\n/**\n * The number of minor-unit digits of a currency, from the platform (`Intl`; no currency table is shipped) or from\n * `defineCurrency`: 2 for EUR, 0 for JPY, 3 for KWD.\n *\n * @example currencyDigits('EUR') // => 2\n * @example currencyDigits('JPY') // => 0\n * @example currencyDigits('KWD') // => 3\n */\nexport function currencyDigits(code: CurrencyCode): number {\n return digitsOf('currencyDigits', code)\n}\n\n/**\n * Whether `code` is a known currency: an upper-case ISO 4217 code the platform knows, or one registered with\n * `defineCurrency`. Never throws.\n *\n * @example isCurrency('EUR') // => true\n * @example isCurrency('eur') // => false\n * @example isCurrency('XXXX') // => false\n */\nexport function isCurrency(code: string): boolean {\n return typeof code === 'string' && (registry.has(code) || platformDigits(code) !== undefined)\n}\n\n/**\n * Register a currency the platform does not know (crypto, loyalty points, a test currency): `defineCurrency('PTS', { digits: 0 })`.\n * The code is 2 to 12 upper-case letters or digits starting with a letter. Registering the same code again with the same\n * digits is fine; with different digits it throws, as does changing an ISO currency's digits. The registry holds at most\n * 64 currencies.\n *\n * @example defineCurrency('PTS', { digits: 0 }); currencyDigits('PTS') // => 0\n */\nexport function defineCurrency(code: string, spec: { digits: number }): void {\n const ok = typeof code === 'string' && code.length >= 2 && code.length <= 12 && code.charCodeAt(0) - 65 >>> 0 < 26 && /^[A-Z][A-Z0-9]*$/.test(code)\n\n if (!ok) return badValue('defineCurrency', 'a code of 2 to 12 upper-case letters or digits starting with a letter', code, 'Example: defineCurrency(\"PTS\", { digits: 0 }).')\n const digits = spec?.digits\n\n if (typeof digits !== 'number' || !Number.isInteger(digits) || digits < 0 || digits > 30) return badValue('defineCurrency', 'spec.digits to be a whole number from 0 to 30', digits)\n const existing = registry.get(code) ?? platformDigits(code)\n\n if (existing !== undefined && existing !== digits) {\n return badRange('defineCurrency', `${code} is already defined with ${existing} digits and cannot be redefined with ${digits}. Pick another code for a different currency.`)\n }\n if (registry.has(code)) return\n if (registry.size >= LIMIT) return badRange('defineCurrency', `at most ${LIMIT} currencies can be registered, got ${show(code)} as number ${LIMIT + 1}. This is a registry for a few custom currencies, not a table.`)\n registry.set(code, digits)\n}\n\n/** Test hook: how many currencies are registered, and how many platform digit counts are remembered. */\nexport function _currencyStats(): { registered: number; remembered: number } {\n return { registered: registry.size, remembered: platform.size }\n}\n\n/** Test hook: forget every registered currency and remembered digit count. */\nexport function _resetCurrencies(): void {\n registry.clear()\n platform.clear()\n iso = undefined\n}\n","import { type CurrencyCode, digitsOf } from './currency'\nimport { badRange, badValue } from './errors'\nimport { checkMode, divRound, formatScaled, MAX_DIGITS, pow10, readDecimal, type RoundingMode, type Scaled, toScaled, wholeIn } from './scaled'\n\n/** Exact money as plain data: a canonical decimal string with exactly the currency's minor digits, and its currency code. */\nexport interface Money {\n readonly amount: string\n readonly currency: CurrencyCode\n}\n\nconst MONEY_HINT = 'a Money such as { amount: \"9.99\", currency: \"EUR\" }'\n\n// ─── reading and writing minor units ──────────────────────────────────────────────────────────────────────────────────────\n// A Money amount is minor units written with a decimal point. Reading it is one char-code loop that also validates it; an\n// amount of 15 digits or fewer becomes a `number` (so add, subtract and compare allocate nothing), longer ones a `bigint`.\n\n/** The digits of a Money's currency, after checking it is shaped like one. */\nfunction digitsOfMoney(fn: string, m: unknown): number {\n if (typeof m !== 'object' || m === null || typeof (m as Money).amount !== 'string' || typeof (m as Money).currency !== 'string') {\n return badValue(fn, MONEY_HINT, m, 'Check data with isMoney() before using it.')\n }\n\n return digitsOf(fn, (m as Money).currency)\n}\n\nfunction notCanonical(fn: string, m: Money, digits: number): never {\n return badValue(fn, `an amount written with exactly ${digits} fraction digit${digits === 1 ? '' : 's'} for ${m.currency}`, m.amount, 'Build a Money with money(), fromMinor() or zero(), and check data with isMoney().')\n}\n\n/** The minor units of an amount: a `number` when it has at most 15 digits, else a `bigint`. Validates the canonical shape. */\n/** The cheap checks of a canonical amount: length, a dot where the digits say, an integer part without a leading zero. */\nfunction shapeOk(text: string, start: number, dot: number, digits: number): boolean {\n const intEnd = digits > 0 ? dot : text.length\n\n if (text.length > MAX_DIGITS + 2 || intEnd - start < 1) return false\n if (digits > 0 && text.charCodeAt(dot) !== 46) return false\n\n return intEnd - start === 1 || text.charCodeAt(start) !== 48\n}\n\nfunction readMinor(fn: string, m: Money, digits: number): number | bigint {\n const text = m.amount\n const len = text.length\n const neg = len > 0 && text.charCodeAt(0) === 45\n const start = neg ? 1 : 0\n const dot = digits > 0 ? len - digits - 1 : -1\n\n if (!shapeOk(text, start, dot, digits)) return notCanonical(fn, m, digits)\n let n = 0\n let nonzero = false\n\n for (let i = start; i < len; i++) {\n if (i === dot) continue\n const d = text.charCodeAt(i) - 48\n\n if (d >>> 0 > 9) return notCanonical(fn, m, digits)\n n = n * 10 + d\n if (d !== 0) nonzero = true\n }\n if (neg && !nonzero) return notCanonical(fn, m, digits)\n if (len - start - (digits > 0 ? 1 : 0) <= 15) return neg ? -n : n\n const big = BigInt(digits > 0 ? text.slice(start, dot) + text.slice(dot + 1) : text.slice(start))\n\n return neg ? -big : big\n}\n\n/** An amount's minor units as a bigint, for the paths that need one. */\nfunction minorBig(fn: string, m: Money, digits: number): bigint {\n const v = readMinor(fn, m, digits)\n\n return typeof v === 'bigint' ? v : BigInt(v)\n}\n\nfunction writeMinor(minor: number | bigint, digits: number): string {\n const neg = minor < 0\n let text = String(neg ? -minor : minor)\n\n if (digits > 0) {\n if (text.length <= digits) text = '0'.repeat(digits - text.length + 1) + text\n text = `${text.slice(0, text.length - digits)}.${text.slice(text.length - digits)}`\n }\n\n return neg ? `-${text}` : text\n}\n\nfunction make(minor: number | bigint, currency: CurrencyCode, digits: number): Money {\n return { amount: writeMinor(minor, digits), currency }\n}\n\nfunction mixed(fn: string, a: Money, b: Money): never {\n return badRange(fn, `cannot combine ${a.currency} with ${b.currency}: a Money has one currency. Convert one side first with convert(money, \"${a.currency}\", rate).`)\n}\n\n/** Check both are Money of one currency and return its digits. */\nfunction pair(fn: string, a: Money, b: Money): number {\n const digits = digitsOfMoney(fn, a)\n\n digitsOfMoney(fn, b)\n if (a.currency !== b.currency) return mixed(fn, a, b)\n\n return digits\n}\n\n// ─── construct and convert ────────────────────────────────────────────────────────────────────────────────────────────────\n\n/** Options of `money`, `multiply`, `divide`, `percentage`, `convert`. */\nexport interface RoundingOptions {\n /** How an inexact result is rounded to the currency's digits. Default `'halfExpand'` (round half away from zero). */\n rounding?: RoundingMode\n}\n\n/** Options of `money`: without `rounding`, a value with more decimals than the currency has throws. */\nexport interface MoneyOptions {\n /** Round an amount with too many decimals instead of throwing. */\n rounding?: RoundingMode\n}\n\n/** What `toMinorScaled` needs to know about the call: the currency, the explicit rounding, and the value as it was given. */\ninterface MinorContext {\n currency: string\n digits: number\n mode: RoundingMode | undefined\n original: unknown\n}\n\nfunction toMinorScaled(fn: string, value: Scaled, ctx: MinorContext): bigint {\n const { currency, digits, mode, original } = ctx\n\n if (value.s <= digits) return value.n * pow10(digits - value.s)\n const unit = pow10(value.s - digits)\n\n if (value.n % unit === 0n) return value.n / unit\n if (mode !== undefined) return divRound(value.n, unit, mode)\n const why = typeof original === 'number'\n ? `${String(original)} has more decimals than ${currency} has (${digits}): that is floating-point noise (0.1 + 0.2 is 0.30000000000000004 in binary floating point), not an amount.`\n : `${JSON.stringify(original)} has more decimals than ${currency} has (${digits}), so it would lose value.`\n\n return badRange(fn, `${why} Round it deliberately: money(x, \"${currency}\", { rounding: \"halfExpand\" }). Better, keep amounts as decimal strings or minor units.`)\n}\n\n/**\n * Build a Money. A string is exact; a number is read by its shortest round-trip text (`9.99` is exactly 9.99, not the binary\n * float near it); a bigint is whole units. A value with more decimals than the currency has throws unless `rounding` is given\n * (so `money(0.1 + 0.2, 'EUR')` throws and explains floating point, instead of hiding the bug). The amount of the result has\n * exactly the currency's digits: `\"9.90\"`, `\"100\"` for JPY, `\"0.123\"` for KWD.\n *\n * @example money(9.99, 'EUR') // => { amount: '9.99', currency: 'EUR' }\n * @example money('10', 'EUR') // => { amount: '10.00', currency: 'EUR' }\n * @example money(100, 'JPY') // => { amount: '100', currency: 'JPY' }\n * @example money(0.1 + 0.2, 'EUR', { rounding: 'halfExpand' }) // => { amount: '0.30', currency: 'EUR' }\n */\nexport function money(amount: number | string | bigint, currency: CurrencyCode, options?: MoneyOptions): Money {\n const digits = digitsOf('money', currency)\n const mode = options?.rounding === undefined ? undefined : checkMode('money', options.rounding)\n const value = toScaled('money', 'amount', amount)\n\n return { amount: formatScaled(toMinorScaled('money', value, { currency, digits, mode, original: amount }), digits), currency }\n}\n\n/**\n * A Money from minor units (cents): `fromMinor(999, 'EUR')` is 9.99. A number must be a safe integer; use a bigint or a\n * digit string above 2^53.\n *\n * @example fromMinor(999, 'EUR') // => { amount: '9.99', currency: 'EUR' }\n * @example fromMinor('123456789012345678901', 'EUR') // => { amount: '1234567890123456789.01', currency: 'EUR' }\n */\nexport function fromMinor(units: number | bigint | string, currency: CurrencyCode): Money {\n const digits = digitsOf('fromMinor', currency)\n let n: bigint\n\n if (typeof units === 'bigint') n = units\n else if (typeof units === 'number') {\n if (!Number.isSafeInteger(units)) return badValue('fromMinor', 'a safe integer number of minor units', units, 'Above 2^53 a number is not exact: pass a bigint or a string of digits.')\n n = BigInt(units)\n } else {\n const parsed = typeof units === 'string' ? readDecimal('fromMinor', units, true) : null\n\n if (parsed === null || parsed.s !== 0) return badValue('fromMinor', 'minor units as a whole number', units)\n n = parsed.n\n }\n\n return { amount: formatScaled(n, digits), currency }\n}\n\n/**\n * The amount in minor units as a bigint: `toMinor(money('9.99', 'EUR'))` is `999n`.\n *\n * @example toMinor(money('9.99', 'EUR')) // => 999n\n */\nexport function toMinor(m: Money): bigint {\n return minorBig('toMinor', m, digitsOfMoney('toMinor', m))\n}\n\n/**\n * The amount in minor units as a number; throws beyond the safe integer range, where a number would not be exact.\n *\n * @example toMinorNumber(money('9.99', 'EUR')) // => 999\n */\nexport function toMinorNumber(m: Money): number {\n const v = readMinor('toMinorNumber', m, digitsOfMoney('toMinorNumber', m))\n\n if (typeof v === 'number') return v\n\n return v >= -9007199254740991n && v <= 9007199254740991n ? Number(v) : badRange('toMinorNumber', `${m.amount} ${m.currency} is ${v} minor units, beyond the safe integer range of a number. Use toMinor(), which returns a bigint.`)\n}\n\n/**\n * Whether `x` is a Money: exactly the fields `amount` and `currency`, a known currency, and a canonical amount with exactly\n * that currency's digits. Never throws.\n *\n * @example isMoney({ amount: '9.99', currency: 'EUR' }) // => true\n * @example isMoney({ amount: '9.9', currency: 'EUR' }) // => false\n * @example isMoney({ amount: 9.99, currency: 'EUR' }) // => false\n */\nexport function isMoney(x: unknown): x is Money {\n try {\n if (typeof x !== 'object' || x === null || Object.keys(x).length !== 2) return false\n const m = x as Money\n\n if (typeof m.amount !== 'string' || typeof m.currency !== 'string') return false\n readMinor('isMoney', m, digitsOf('isMoney', m.currency))\n\n return true\n } catch {\n return false\n }\n}\n\n/**\n * Zero in a currency.\n *\n * @example zero('EUR') // => { amount: '0.00', currency: 'EUR' }\n */\nexport function zero(currency: CurrencyCode): Money {\n return { amount: writeMinor(0, digitsOf('zero', currency)), currency }\n}\n\n// ─── arithmetic ───────────────────────────────────────────────────────────────────────────────────────────────────────────\n\nfunction combine(fn: string, a: Money, b: Money, sign: 1 | -1): Money {\n const digits = pair(fn, a, b)\n const x = readMinor(fn, a, digits)\n const y = readMinor(fn, b, digits)\n\n if (typeof x === 'number' && typeof y === 'number') {\n const r = sign === 1 ? x + y : x - y\n\n if (Number.isSafeInteger(r)) return make(r, a.currency, digits)\n }\n const bx = typeof x === 'bigint' ? x : BigInt(x)\n const by = typeof y === 'bigint' ? y : BigInt(y)\n\n return make(sign === 1 ? bx + by : bx - by, a.currency, digits)\n}\n\n/**\n * Exact sum of two amounts of one currency. Mixing currencies throws and names both.\n *\n * @example add(money('0.10', 'EUR'), money('0.20', 'EUR')) // => { amount: '0.30', currency: 'EUR' }\n */\nexport function add(a: Money, b: Money): Money {\n return combine('add', a, b, 1)\n}\n\n/**\n * Exact difference `a - b` of two amounts of one currency.\n *\n * @example subtract(money('1.00', 'EUR'), money('0.01', 'EUR')) // => { amount: '0.99', currency: 'EUR' }\n */\nexport function subtract(a: Money, b: Money): Money {\n return combine('subtract', a, b, -1)\n}\n\n/**\n * The same amount with the opposite sign.\n *\n * @example negate(money('5', 'EUR')) // => { amount: '-5.00', currency: 'EUR' }\n */\nexport function negate(m: Money): Money {\n const digits = digitsOfMoney('negate', m)\n const v = readMinor('negate', m, digits)\n\n return make(typeof v === 'number' ? -v + 0 : -v, m.currency, digits)\n}\n\n/**\n * The amount without its sign.\n *\n * @example abs(money('-5', 'EUR')) // => { amount: '5.00', currency: 'EUR' }\n */\nexport function abs(m: Money): Money {\n const digits = digitsOfMoney('abs', m)\n const v = readMinor('abs', m, digits)\n\n return make(v < 0 ? -v : v, m.currency, digits)\n}\n\n/**\n * The sum of a list of one currency. An empty list needs `currency`.\n *\n * @example sum([money('1.10', 'EUR'), money('2.20', 'EUR')]) // => { amount: '3.30', currency: 'EUR' }\n * @example sum([], 'EUR') // => { amount: '0.00', currency: 'EUR' }\n */\nexport function sum(list: Iterable<Money>, currency?: CurrencyCode): Money {\n if (list === null || list === undefined || typeof (list as Iterable<Money>)[Symbol.iterator] !== 'function') return badValue('sum', 'a list of Money', list)\n let code = currency\n let digits = code === undefined ? -1 : digitsOf('sum', code)\n let total = 0n\n\n for (const m of list) {\n if (code === undefined) {\n digits = digitsOfMoney('sum', m)\n code = m.currency\n } else if (digitsOfMoney('sum', m) !== digits || m.currency !== code) {\n return badRange('sum', `cannot sum ${code} with ${(m as Money).currency}: a list of Money must be one currency. Convert first with convert().`)\n }\n total += minorBig('sum', m, digits)\n }\n\n return code === undefined ? badRange('sum', 'an empty list has no currency. Pass it: sum([], \"EUR\").') : make(total, code, digits)\n}\n\nfunction rounding(fn: string, options: RoundingOptions | undefined): RoundingMode {\n return options?.rounding === undefined ? 'halfExpand' : checkMode(fn, options.rounding)\n}\n\n/**\n * The amount times a plain number, rounded to the currency's digits (default `'halfExpand'`). The factor is a pure number: a\n * number is read by its shortest text, so `1.21` is exactly 1.21; prefer a string. For a Money times a Money there is no\n * operation, because it has no meaning.\n *\n * @example multiply(money('19.99', 'EUR'), 3) // => { amount: '59.97', currency: 'EUR' }\n * @example multiply(money('10.00', 'EUR'), '1.21') // => { amount: '12.10', currency: 'EUR' }\n * @example multiply(money('0.05', 'EUR'), '0.5') // => { amount: '0.03', currency: 'EUR' }\n */\nexport function multiply(m: Money, factor: number | string | bigint, options?: RoundingOptions): Money {\n const digits = digitsOfMoney('multiply', m)\n const f = toScaled('multiply', 'factor', factor)\n const mode = rounding('multiply', options)\n\n return make(divRound(minorBig('multiply', m, digits) * f.n, pow10(f.s), mode), m.currency, digits)\n}\n\n/**\n * The amount divided by a plain number, rounded to the currency's digits. A zero divisor throws. To split an amount without\n * losing a cent use `allocate` or `split`: dividing three ways and multiplying back does not give the amount.\n *\n * @example divide(money('10.00', 'EUR'), 3) // => { amount: '3.33', currency: 'EUR' }\n */\nexport function divide(m: Money, divisor: number | string | bigint, options?: RoundingOptions): Money {\n const digits = digitsOfMoney('divide', m)\n const d = toScaled('divide', 'divisor', divisor)\n const mode = rounding('divide', options)\n\n if (d.n === 0n) return badRange('divide', `the divisor ${JSON.stringify(String(divisor))} is zero`)\n\n return make(divRound(minorBig('divide', m, digits) * pow10(d.s), d.n, mode), m.currency, digits)\n}\n\n/**\n * `percent` percent of an amount, rounded to the currency's digits.\n *\n * @example percentage(money('200.00', 'EUR'), 21) // => { amount: '42.00', currency: 'EUR' }\n * @example percentage(money('9.99', 'EUR'), '7.5') // => { amount: '0.75', currency: 'EUR' }\n */\nexport function percentage(m: Money, percent: number | string | bigint, options?: RoundingOptions): Money {\n const digits = digitsOfMoney('percentage', m)\n const p = toScaled('percentage', 'percent', percent)\n const mode = rounding('percentage', options)\n\n return make(divRound(minorBig('percentage', m, digits) * p.n, pow10(p.s) * 100n, mode), m.currency, digits)\n}\n\nfunction ratiosOf(fn: string, ratios: unknown): bigint[] {\n if (!Array.isArray(ratios) || ratios.length === 0 || ratios.length > 100_000) {\n return badValue(fn, 'a non-empty array of ratios such as [1, 1, 2] or [\"0.5\", \"0.5\"]', ratios)\n }\n const parsed = ratios.map((r) => toScaled(fn, 'every ratio', r))\n const scale = parsed.reduce((s, r) => (r.s > s ? r.s : s), 0)\n const ints = parsed.map((r) => r.n * pow10(scale - r.s))\n\n if (ints.some((n) => n < 0n)) return badRange(fn, `ratios must not be negative, got ${JSON.stringify(ratios.map(String))}`)\n if (ints.every((n) => n === 0n)) return badRange(fn, `the ratios are all zero (${JSON.stringify(ratios.map(String))}), so there is nothing to share by. Give at least one ratio above zero.`)\n\n return ints\n}\n\n/**\n * Share an amount by ratios so that the parts sum EXACTLY to the amount. Each part is its floor share in minor units; the\n * minor units left over go one each to the parts with the largest fractional remainders, ties to the first. A negative amount\n * is shared by its absolute value and the parts take its sign. A ratio of zero gets zero. All-zero or negative ratios throw.\n * Each part is within one minor unit of its exact share. Reordering the ratios reorders the parts, but a tie can move a cent.\n *\n * @example allocate(money('100.00', 'EUR'), [1, 1, 1]).map((p) => p.amount) // => ['33.34', '33.33', '33.33']\n * @example allocate(money('0.05', 'EUR'), [3, 7]).map((p) => p.amount) // => ['0.02', '0.03']\n * @example allocate(money('10.00', 'EUR'), [0, 1]).map((p) => p.amount) // => ['0.00', '10.00']\n */\nexport function allocate(m: Money, ratios: readonly (number | string)[]): Money[] {\n const digits = digitsOfMoney('allocate', m)\n const weights = ratiosOf('allocate', ratios)\n const minor = minorBig('allocate', m, digits)\n const negative = minor < 0n\n const total = negative ? -minor : minor\n let weightSum = 0n\n\n for (const w of weights) weightSum += w\n const floors: bigint[] = []\n const rests: bigint[] = []\n let given = 0n\n\n for (const w of weights) {\n const product = total * w\n\n floors.push(product / weightSum)\n rests.push(product % weightSum)\n given += product / weightSum\n }\n const order = weights.map((_, i) => i).sort((i, j) => (rests[i]! === rests[j]! ? i - j : rests[i]! > rests[j]! ? -1 : 1))\n\n for (let k = 0n; k < total - given; k++) floors[order[Number(k)]!]! += 1n\n\n return floors.map((part) => make(negative ? -part : part, m.currency, digits))\n}\n\n/**\n * Split an amount into `parts` equal parts that sum exactly to it: the first parts get the extra cent.\n *\n * @example split(money('100.00', 'EUR'), 3).map((p) => p.amount) // => ['33.34', '33.33', '33.33']\n */\nexport function split(m: Money, parts: number): Money[] {\n const n = wholeIn('split', 'parts', parts, 1, 100_000)\n\n return allocate(m, new Array<number>(n).fill(1))\n}\n\n/** Options of `ratio`. */\nexport interface RatioOptions {\n /** Digits after the decimal point. Default 10. */\n scale?: number\n /** Default `'halfExpand'`. */\n rounding?: RoundingMode\n}\n\n/**\n * `a / b` as a decimal string with trailing zeros removed, rounded to `scale` digits (default 10). Both amounts must be one\n * currency; a zero `b` throws.\n *\n * @example ratio(money('1.00', 'EUR'), money('4.00', 'EUR')) // => '0.25'\n * @example ratio(money('1.00', 'EUR'), money('3.00', 'EUR'), { scale: 4 }) // => '0.3333'\n */\nexport function ratio(a: Money, b: Money, options?: RatioOptions): string {\n const digits = pair('ratio', a, b)\n const scale = options?.scale === undefined ? 10 : wholeIn('ratio', 'scale', options.scale, 0, 1000)\n const mode = options?.rounding === undefined ? 'halfExpand' : checkMode('ratio', options.rounding)\n const y = minorBig('ratio', b, digits)\n\n if (y === 0n) return badRange('ratio', `the second amount is zero (${b.amount} ${b.currency}), so the ratio is undefined`)\n const text = formatScaled(divRound(minorBig('ratio', a, digits) * pow10(scale), y, mode), scale)\n\n return scale === 0 || !text.includes('.') ? text : text.replace(/0+$/, '').replace(/\\.$/, '')\n}\n\n// ─── compare ──────────────────────────────────────────────────────────────────────────────────────────────────────────────\n\n/**\n * -1, 0 or 1. Different currencies throw (they cannot be ordered without a rate).\n *\n * @example compare(money('1.00', 'EUR'), money('2.00', 'EUR')) // => -1\n */\nexport function compare(a: Money, b: Money): -1 | 0 | 1 {\n const digits = pair('compare', a, b)\n const x = readMinor('compare', a, digits)\n const y = readMinor('compare', b, digits)\n\n return x < y ? -1 : x > y ? 1 : 0\n}\n\n/**\n * Whether two amounts are equal. Amounts of different currencies are not equal (this does not throw).\n *\n * @example equals(money('1.5', 'EUR'), money('1.50', 'EUR')) // => true\n * @example equals(money('1', 'EUR'), money('1', 'USD')) // => false\n */\nexport function equals(a: Money, b: Money): boolean {\n const digits = digitsOfMoney('equals', a)\n const other = digitsOfMoney('equals', b)\n\n if (a.currency !== b.currency) return false\n readMinor('equals', a, digits)\n readMinor('equals', b, other)\n\n return a.amount === b.amount\n}\n\nfunction extreme(fn: string, list: readonly Money[], sign: -1 | 1): Money {\n if (list.length === 0) return badRange(fn, 'needs at least one amount')\n let best = list[0]!\n\n digitsOfMoney(fn, best)\n for (let i = 1; i < list.length; i++) {\n if (compare(list[i]!, best) === sign) best = list[i]!\n }\n\n return best\n}\n\n/**\n * The smallest amount. At least one is required; currencies must match.\n *\n * @example min(money('3', 'EUR'), money('2', 'EUR')) // => { amount: '2.00', currency: 'EUR' }\n */\nexport function min(...amounts: [Money, ...Money[]]): Money {\n return extreme('min', amounts, -1)\n}\n\n/**\n * The largest amount. At least one is required; currencies must match.\n *\n * @example max(money('3', 'EUR'), money('2', 'EUR')) // => { amount: '3.00', currency: 'EUR' }\n */\nexport function max(...amounts: [Money, ...Money[]]): Money {\n return extreme('max', amounts, 1)\n}\n\n/**\n * Whether the amount is zero.\n *\n * @example isZero(zero('EUR')) // => true\n */\nexport function isZero(m: Money): boolean {\n return readMinor('isZero', m, digitsOfMoney('isZero', m)) == 0\n}\n\n/**\n * Whether the amount is above zero.\n *\n * @example isPositive(money('0.01', 'EUR')) // => true\n */\nexport function isPositive(m: Money): boolean {\n return readMinor('isPositive', m, digitsOfMoney('isPositive', m)) > 0\n}\n\n/**\n * Whether the amount is below zero.\n *\n * @example isNegative(money('-0.01', 'EUR')) // => true\n */\nexport function isNegative(m: Money): boolean {\n return readMinor('isNegative', m, digitsOfMoney('isNegative', m)) < 0\n}\n\n// ─── rounding and conversion ──────────────────────────────────────────────────────────────────────────────────────────────\n\n/** Options of `round`. */\nexport interface MoneyRoundOptions {\n /** Keep fewer fraction digits than the currency has (`0` rounds to whole units). */\n digits?: number\n /** Round to a multiple of this amount (`'0.05'` for cash rounding in CHF). Not together with `digits`. */\n increment?: string | number\n /** Default `'halfExpand'`. */\n mode?: RoundingMode\n}\n\n/**\n * Round to fewer digits or to a multiple of an increment (cash rounding), by `mode` (default `'halfExpand'`, round half away\n * from zero; `'halfEven'` is banker's rounding). With no options it is the amount itself, because a Money always has exactly\n * its currency's digits.\n *\n * @example round(money('12.34', 'EUR'), { digits: 0 }) // => { amount: '12.00', currency: 'EUR' }\n * @example round(money('1.23', 'CHF'), { increment: '0.05' }) // => { amount: '1.25', currency: 'CHF' }\n * @example round(money('2.50', 'EUR'), { digits: 0, mode: 'halfEven' }) // => { amount: '2.00', currency: 'EUR' }\n */\nexport function round(m: Money, options?: MoneyRoundOptions): Money {\n const digits = digitsOfMoney('round', m)\n const mode = options?.mode === undefined ? 'halfExpand' : checkMode('round', options.mode)\n const minor = minorBig('round', m, digits)\n\n if (options?.increment !== undefined && options.digits !== undefined) return badValue('round', 'either digits or increment', options, 'Pass one: digits to keep fewer digits, increment for cash rounding.')\n let unit = 1n\n\n if (options?.increment !== undefined) {\n const inc = toScaled('round', 'increment', options.increment)\n const scaled = inc.n * pow10(digits)\n\n if (inc.n <= 0n) return badRange('round', `increment must be greater than zero, got ${JSON.stringify(String(options.increment))}`)\n if (scaled % pow10(inc.s) !== 0n) return badRange('round', `the increment ${JSON.stringify(String(options.increment))} is smaller than a ${m.currency} minor unit (${digits} digits)`)\n unit = scaled / pow10(inc.s)\n } else if (options?.digits !== undefined) {\n const keep = wholeIn('round', 'digits', options.digits, 0, 1000)\n\n if (keep < digits) unit = pow10(digits - keep)\n }\n\n return make(divRound(minor, unit, mode) * unit, m.currency, digits)\n}\n\n/**\n * Convert to another currency with a rate (`1 unit of m.currency = rate units of to`), rounded to the target's digits. Give\n * the rate as a decimal string; a number is read by its shortest text. Keep `{ from, to, rate }` next to the result: it is the\n * audit trail.\n *\n * @example convert(money('100.00', 'EUR'), 'USD', '1.0842') // => { amount: '108.42', currency: 'USD' }\n * @example convert(money('100.00', 'EUR'), 'JPY', '162.5') // => { amount: '16250', currency: 'JPY' }\n */\nexport function convert(m: Money, to: CurrencyCode, rate: number | string | bigint, options?: RoundingOptions): Money {\n const from = digitsOfMoney('convert', m)\n const target = digitsOf('convert', to)\n const r = toScaled('convert', 'rate', rate)\n const mode = rounding('convert', options)\n\n if (r.n <= 0n) return badRange('convert', `the rate must be greater than zero, got ${JSON.stringify(String(rate))}`)\n\n return make(divRound(minorBig('convert', m, from) * r.n * pow10(target), pow10(from + r.s), mode), to, target)\n}\n"],"mappings":";;;;AAMA,MAAM,QAAQ;AACd,MAAM,2BAAW,IAAI,IAAoB;AACzC,MAAM,2BAAW,IAAI,IAAoB;AACzC,IAAI;AAEJ,SAAS,WAA+B;CACtC,IAAI,QAAQ,QAAW;EACrB,MAAM,OAAQ,KAA2D,oBAAoB,UAAU;EAEvG,MAAM,SAAS,SAAY,OAAO,IAAI,IAAI,IAAI;CAChD;CAEA,OAAO;AACT;AAEA,SAAS,WAAW,MAAuB;CACzC,OAAO,KAAK,WAAW,KAAK,KAAK,WAAW,CAAC,IAAI,OAAO,IAAI,MAAM,KAAK,WAAW,CAAC,IAAI,OAAO,IAAI,MAAM,KAAK,WAAW,CAAC,IAAI,OAAO,IAAI;AAC1I;;AAGA,SAAS,eAAe,MAAkC;CACxD,MAAM,MAAM,SAAS,IAAI,IAAI;CAE7B,IAAI,QAAQ,QAAW,OAAO;CAC9B,IAAI,CAAC,WAAW,IAAI,GAAG,OAAO;CAC9B,MAAM,QAAQ,SAAS;CAEvB,IAAI,UAAU,QAAQ,CAAC,MAAM,IAAI,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AS,WAAW,OAAO;CAExC,IAAI,EAAE,KAAK,IAAI,OAAO,SAAS,WAAW,2CAA2C,KAAK,UAAU,OAAO,IAAI,CAAC,GAAG;CAEnH,OAAO,KAAK,SAAS,SAAS,WAAW,GAAG,IAAI,IAAI,EAAE,IAAI,MAAM,MAAM,GAAG,MAAM,OAAO,EAAE,CAAC,GAAG,IAAI,GAAG,IAAI,MAAM;AAC/G"}
@@ -0,0 +1,195 @@
1
+ // src/errors.ts
2
+ /** A short, safe rendering of any value for an error message: it never throws, whatever the value's `toString` does. */
3
+ function show(value) {
4
+ try {
5
+ const text = typeof value === "string" ? JSON.stringify(value) : typeof value === "object" && value !== null ? Object.prototype.toString.call(value) : typeof value === "bigint" ? `${value}n` : String(value);
6
+ return text.length > 60 ? `${text.slice(0, 57)}...` : text;
7
+ } catch {
8
+ return "(a value that cannot be printed)";
9
+ }
10
+ }
11
+ /** A value of the wrong shape: a programmer error, so it throws a message that names the function, the value and the fix. */
12
+ function badValue(fn, expected, got, fix = "") {
13
+ throw new TypeError(`[Pyreon] ${fn}: expected ${expected}, got ${show(got)}.${fix === "" ? "" : ` ${fix}`}`);
14
+ }
15
+ /** A well-formed value that is not allowed (out of range, a mix of currencies, a zero divisor). */
16
+ function badRange(fn, message) {
17
+ throw new RangeError(`[Pyreon] ${fn}: ${message}`);
18
+ }
19
+
20
+ // src/scaled.ts
21
+ /** The most digits an input may have (and the largest scale an option may ask for): a guard against `1e999999999`. */
22
+ const MAX_DIGITS = 4096;
23
+ const MODES = [
24
+ "ceil",
25
+ "floor",
26
+ "expand",
27
+ "trunc",
28
+ "halfCeil",
29
+ "halfFloor",
30
+ "halfExpand",
31
+ "halfTrunc",
32
+ "halfEven"
33
+ ];
34
+ function checkMode(fn, mode) {
35
+ return typeof mode === "string" && MODES.includes(mode) ? mode : badValue(fn, `a rounding mode (${MODES.join(", ")})`, mode, `The default is 'halfExpand' (round half away from zero); 'halfEven' is banker's rounding.`);
36
+ }
37
+ const POWERS = [1n];
38
+ /** `10n ** k`, cached for small `k` (a fixed table of at most 64 entries). */
39
+ function pow10(k) {
40
+ if (k < 64) {
41
+ for (let i = POWERS.length; i <= k; i++) POWERS.push(POWERS[i - 1] * 10n);
42
+ return POWERS[k];
43
+ }
44
+ return 10n ** BigInt(k);
45
+ }
46
+ /** The index after the run of ASCII digits that starts at `from`. */
47
+ function digitsEnd(text, from) {
48
+ let i = from;
49
+ while (i < text.length && text.charCodeAt(i) - 48 >>> 0 <= 9) i++;
50
+ return i;
51
+ }
52
+ /**
53
+ * Read decimal text. Strict mode accepts exactly the canonical form (`-?(0|[1-9][0-9]*)(\.[0-9]+)?`, no `-0`). Lenient mode
54
+ * also accepts a leading `+`, `.5`, `5.`, leading zeros and an exponent (`1e-3`, `1.5E+2`). Returns `null` when the text is not
55
+ * a decimal in that mode, and throws a RangeError when it is one that is larger than `MAX_DIGITS`.
56
+ */
57
+ function readDecimal(fn, text, lenient) {
58
+ const len = text.length;
59
+ let i = 0;
60
+ let neg = false;
61
+ if (len === 0) return null;
62
+ const first = text.charCodeAt(0);
63
+ if (first === 45) {
64
+ neg = true;
65
+ i = 1;
66
+ } else if (first === 43 && lenient) i = 1;
67
+ const intStart = i;
68
+ i = digitsEnd(text, i);
69
+ const intLen = i - intStart;
70
+ let fracStart = i;
71
+ let fracLen = 0;
72
+ if (i < len && text.charCodeAt(i) === 46) {
73
+ fracStart = ++i;
74
+ i = digitsEnd(text, i);
75
+ fracLen = i - fracStart;
76
+ if (fracLen === 0 && !lenient) return null;
77
+ }
78
+ if (intLen === 0 && fracLen === 0) return null;
79
+ const parts = {
80
+ text,
81
+ neg,
82
+ intStart,
83
+ intLen,
84
+ fracStart,
85
+ fracLen,
86
+ exp: 0
87
+ };
88
+ if (!lenient) return i === len && intLen > 0 ? strictShape(fn, parts) : null;
89
+ if (i < len && (text.charCodeAt(i) | 32) === 101) {
90
+ const end = readExponent(fn, text, i + 1, parts);
91
+ if (end < 0) return null;
92
+ i = end;
93
+ }
94
+ return i === len ? build(fn, parts) : null;
95
+ }
96
+ /** Read the exponent digits that start at `from` into `parts.exp`; returns the end index, or -1 when there are none. */
97
+ function readExponent(fn, text, from, parts) {
98
+ let j = from;
99
+ let eneg = false;
100
+ if (j < text.length && (text.charCodeAt(j) === 43 || text.charCodeAt(j) === 45)) eneg = text.charCodeAt(j++) === 45;
101
+ const expStart = j;
102
+ j = digitsEnd(text, j);
103
+ if (j === expStart) return -1;
104
+ if (j - expStart > 9) return badRange(fn, `the exponent in ${JSON.stringify(text.slice(0, 40))} is too large`);
105
+ parts.exp = Number(text.slice(expStart, j)) * (eneg ? -1 : 1);
106
+ return j;
107
+ }
108
+ function strictShape(fn, parts) {
109
+ if (parts.intLen > 1 && parts.text.charCodeAt(parts.intStart) === 48) return null;
110
+ const scaled = build(fn, parts);
111
+ return scaled !== null && scaled.n === 0n && parts.neg ? null : scaled;
112
+ }
113
+ function build(fn, parts) {
114
+ const { text, neg, intStart, intLen, fracStart, fracLen, exp } = parts;
115
+ let digits = text.slice(intStart, intStart + intLen) + (fracLen > 0 ? text.slice(fracStart, fracStart + fracLen) : "");
116
+ let s = fracLen - exp;
117
+ if (s < 0) {
118
+ if (digits.length - s > 4096) return badRange(fn, `${JSON.stringify(text.slice(0, 40))} has more than ${MAX_DIGITS} digits once its exponent is applied`);
119
+ digits += "0".repeat(-s);
120
+ s = 0;
121
+ }
122
+ if (digits.length > 4096 || s > 4096) return badRange(fn, `${JSON.stringify(text.slice(0, 40))} has more than ${MAX_DIGITS} digits`);
123
+ const n = BigInt(digits);
124
+ return {
125
+ n: neg ? -n : n,
126
+ s
127
+ };
128
+ }
129
+ /** The canonical text of `n / 10^s` with exactly `s` fraction digits. Zero is never written with a sign. */
130
+ function formatScaled(n, s) {
131
+ const neg = n < 0n;
132
+ let digits = (neg ? -n : n).toString();
133
+ if (s > 0) {
134
+ if (digits.length <= s) digits = "0".repeat(s - digits.length + 1) + digits;
135
+ digits = `${digits.slice(0, digits.length - s)}.${digits.slice(digits.length - s)}`;
136
+ }
137
+ return neg ? `-${digits}` : digits;
138
+ }
139
+ /**
140
+ * `n / d` rounded to an integer by `mode`, on integers: the one place rounding is implemented. `d` must not be zero. The
141
+ * quotient truncates toward zero; the remainder says whether the exact value is a tie or on which side of one, and the mode
142
+ * picks between the truncated value and the next integer away from zero.
143
+ */
144
+ function divRound(n, d, mode) {
145
+ if (d < 0n) {
146
+ n = -n;
147
+ d = -d;
148
+ }
149
+ const q = n / d;
150
+ const r = n % d;
151
+ if (r === 0n) return q;
152
+ const negative = n < 0n;
153
+ const away = negative ? q - 1n : q + 1n;
154
+ const twice = (r < 0n ? -r : r) * 2n;
155
+ switch (mode) {
156
+ case "trunc": return q;
157
+ case "expand": return away;
158
+ case "ceil": return negative ? q : away;
159
+ case "floor": return negative ? away : q;
160
+ default:
161
+ if (twice < d) return q;
162
+ if (twice > d) return away;
163
+ return tie(mode, q, away, negative);
164
+ }
165
+ }
166
+ /** The half-way cases of the five `half*` modes. */
167
+ function tie(mode, q, away, negative) {
168
+ if (mode === "halfExpand") return away;
169
+ if (mode === "halfTrunc") return q;
170
+ if (mode === "halfCeil") return negative ? q : away;
171
+ if (mode === "halfFloor") return negative ? away : q;
172
+ return q % 2n === 0n ? q : away;
173
+ }
174
+ /** A whole number in `lo..hi`, or a thrown error naming the function and option. */
175
+ function wholeIn(fn, name, value, lo, hi) {
176
+ return typeof value === "number" && Number.isInteger(value) && value >= lo && value <= hi ? value : badValue(fn, `${name} to be a whole number from ${lo} to ${hi}`, value);
177
+ }
178
+ /**
179
+ * A number, decimal string or bigint as a `Scaled`. A number is read by its shortest round-trip text (`0.1` is exactly one
180
+ * tenth, not the binary float nearest to it); `lenient` text may carry a sign, an exponent and so on.
181
+ */
182
+ function toScaled(fn, what, value) {
183
+ if (typeof value === "bigint") return {
184
+ n: value,
185
+ s: 0
186
+ };
187
+ if (typeof value === "number") {
188
+ if (!Number.isFinite(value)) return badValue(fn, `${what} to be a finite number`, value);
189
+ return readDecimal(fn, Object.is(value, -0) ? "0" : String(value), true);
190
+ }
191
+ return (typeof value === "string" ? readDecimal(fn, value, true) : null) ?? badValue(fn, `${what} to be a number, a decimal string such as "1.21" or a bigint`, value, typeof value === "string" && value.includes(",") ? "Use a dot as the decimal mark, and no thousands separators." : typeof value === "string" && value !== value.trim() ? "Remove the surrounding spaces." : "");
192
+ }
193
+
194
+ export { pow10 as a, wholeIn as c, show as d, formatScaled as i, badRange as l, checkMode as n, readDecimal as o, divRound as r, toScaled as s, MAX_DIGITS as t, badValue as u };
195
+ //# sourceMappingURL=scaled-eXdrPpWS.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"scaled-eXdrPpWS.js","names":[],"sources":["../../src/errors.ts","../../src/scaled.ts"],"sourcesContent":["/** A short, safe rendering of any value for an error message: it never throws, whatever the value's `toString` does. */\nexport function show(value: unknown): string {\n try {\n const text =\n typeof value === 'string'\n ? JSON.stringify(value)\n : typeof value === 'object' && value !== null\n ? Object.prototype.toString.call(value)\n : typeof value === 'bigint'\n ? `${value}n`\n : String(value)\n\n return text.length > 60 ? `${text.slice(0, 57)}...` : text\n } catch {\n return '(a value that cannot be printed)'\n }\n}\n\n/** A value of the wrong shape: a programmer error, so it throws a message that names the function, the value and the fix. */\nexport function badValue(fn: string, expected: string, got: unknown, fix = ''): never {\n throw new TypeError(`[Pyreon] ${fn}: expected ${expected}, got ${show(got)}.${fix === '' ? '' : ` ${fix}`}`)\n}\n\n/** A well-formed value that is not allowed (out of range, a mix of currencies, a zero divisor). */\nexport function badRange(fn: string, message: string): never {\n throw new RangeError(`[Pyreon] ${fn}: ${message}`)\n}\n","import { badRange, badValue } from './errors'\n\n/**\n * Exact decimals as scaled integers: a value is `n / 10^s` with a `bigint` numerator and a whole scale. Parsing and printing\n * read char codes; no regex, no `Number()` on a piece of text, no `BigInt()` on text that could be malformed (a `SyntaxError`\n * never reaches a caller).\n */\nexport interface Scaled {\n /** Signed numerator. */\n n: bigint\n /** Digits after the decimal point. */\n s: number\n}\n\n/** The most digits an input may have (and the largest scale an option may ask for): a guard against `1e999999999`. */\nexport const MAX_DIGITS = 4096\n\n/** The nine rounding modes, named as `Intl.NumberFormat`'s `roundingMode` names them. */\nexport type RoundingMode = 'ceil' | 'floor' | 'expand' | 'trunc' | 'halfCeil' | 'halfFloor' | 'halfExpand' | 'halfTrunc' | 'halfEven'\n\nconst MODES = ['ceil', 'floor', 'expand', 'trunc', 'halfCeil', 'halfFloor', 'halfExpand', 'halfTrunc', 'halfEven']\n\nexport function checkMode(fn: string, mode: unknown): RoundingMode {\n return typeof mode === 'string' && MODES.includes(mode)\n ? (mode as RoundingMode)\n : badValue(fn, `a rounding mode (${MODES.join(', ')})`, mode, `The default is 'halfExpand' (round half away from zero); 'halfEven' is banker's rounding.`)\n}\n\nconst POWERS: bigint[] = [1n]\n\n/** `10n ** k`, cached for small `k` (a fixed table of at most 64 entries). */\nexport function pow10(k: number): bigint {\n if (k < 64) {\n for (let i = POWERS.length; i <= k; i++) POWERS.push(POWERS[i - 1]! * 10n)\n\n return POWERS[k]!\n }\n\n return 10n ** BigInt(k)\n}\n\n/** The index after the run of ASCII digits that starts at `from`. */\nfunction digitsEnd(text: string, from: number): number {\n let i = from\n\n while (i < text.length && text.charCodeAt(i) - 48 >>> 0 <= 9) i++\n\n return i\n}\n\n/**\n * Read decimal text. Strict mode accepts exactly the canonical form (`-?(0|[1-9][0-9]*)(\\.[0-9]+)?`, no `-0`). Lenient mode\n * also accepts a leading `+`, `.5`, `5.`, leading zeros and an exponent (`1e-3`, `1.5E+2`). Returns `null` when the text is not\n * a decimal in that mode, and throws a RangeError when it is one that is larger than `MAX_DIGITS`.\n */\nexport function readDecimal(fn: string, text: string, lenient: boolean): Scaled | null {\n const len = text.length\n let i = 0\n let neg = false\n\n if (len === 0) return null\n const first = text.charCodeAt(0)\n\n if (first === 45) {\n neg = true\n i = 1\n } else if (first === 43 && lenient) i = 1\n const intStart = i\n\n i = digitsEnd(text, i)\n const intLen = i - intStart\n let fracStart = i\n let fracLen = 0\n\n if (i < len && text.charCodeAt(i) === 46) {\n fracStart = ++i\n i = digitsEnd(text, i)\n fracLen = i - fracStart\n if (fracLen === 0 && !lenient) return null\n }\n if (intLen === 0 && fracLen === 0) return null\n const parts: Parts = { text, neg, intStart, intLen, fracStart, fracLen, exp: 0 }\n\n if (!lenient) return i === len && intLen > 0 ? strictShape(fn, parts) : null\n if (i < len && (text.charCodeAt(i) | 32) === 101) {\n const end = readExponent(fn, text, i + 1, parts)\n\n if (end < 0) return null\n i = end\n }\n\n return i === len ? build(fn, parts) : null\n}\n\n/** Where the digits of a number sit in its text. */\ninterface Parts {\n text: string\n neg: boolean\n intStart: number\n intLen: number\n fracStart: number\n fracLen: number\n exp: number\n}\n\n/** Read the exponent digits that start at `from` into `parts.exp`; returns the end index, or -1 when there are none. */\nfunction readExponent(fn: string, text: string, from: number, parts: Parts): number {\n let j = from\n let eneg = false\n\n if (j < text.length && (text.charCodeAt(j) === 43 || text.charCodeAt(j) === 45)) eneg = text.charCodeAt(j++) === 45\n const expStart = j\n\n j = digitsEnd(text, j)\n if (j === expStart) return -1\n if (j - expStart > 9) return badRange(fn, `the exponent in ${JSON.stringify(text.slice(0, 40))} is too large`)\n parts.exp = Number(text.slice(expStart, j)) * (eneg ? -1 : 1)\n\n return j\n}\n\nfunction strictShape(fn: string, parts: Parts): Scaled | null {\n // Canonical: no leading zero before other digits, and no negative zero.\n if (parts.intLen > 1 && parts.text.charCodeAt(parts.intStart) === 48) return null\n const scaled = build(fn, parts)\n\n return scaled !== null && scaled.n === 0n && parts.neg ? null : scaled\n}\n\nfunction build(fn: string, parts: Parts): Scaled | null {\n const { text, neg, intStart, intLen, fracStart, fracLen, exp } = parts\n let digits = text.slice(intStart, intStart + intLen) + (fracLen > 0 ? text.slice(fracStart, fracStart + fracLen) : '')\n let s = fracLen - exp\n\n if (s < 0) {\n if (digits.length - s > MAX_DIGITS) return badRange(fn, `${JSON.stringify(text.slice(0, 40))} has more than ${MAX_DIGITS} digits once its exponent is applied`)\n digits += '0'.repeat(-s)\n s = 0\n }\n if (digits.length > MAX_DIGITS || s > MAX_DIGITS) return badRange(fn, `${JSON.stringify(text.slice(0, 40))} has more than ${MAX_DIGITS} digits`)\n const n = BigInt(digits)\n\n return { n: neg ? -n : n, s }\n}\n\n/** The canonical text of `n / 10^s` with exactly `s` fraction digits. Zero is never written with a sign. */\nexport function formatScaled(n: bigint, s: number): string {\n const neg = n < 0n\n let digits = (neg ? -n : n).toString()\n\n if (s > 0) {\n if (digits.length <= s) digits = '0'.repeat(s - digits.length + 1) + digits\n digits = `${digits.slice(0, digits.length - s)}.${digits.slice(digits.length - s)}`\n }\n\n return neg ? `-${digits}` : digits\n}\n\n/**\n * `n / d` rounded to an integer by `mode`, on integers: the one place rounding is implemented. `d` must not be zero. The\n * quotient truncates toward zero; the remainder says whether the exact value is a tie or on which side of one, and the mode\n * picks between the truncated value and the next integer away from zero.\n */\nexport function divRound(n: bigint, d: bigint, mode: RoundingMode): bigint {\n if (d < 0n) {\n n = -n\n d = -d\n }\n const q = n / d\n const r = n % d\n\n if (r === 0n) return q\n const negative = n < 0n\n const away = negative ? q - 1n : q + 1n\n const twice = (r < 0n ? -r : r) * 2n\n\n switch (mode) {\n case 'trunc':\n return q\n case 'expand':\n return away\n case 'ceil':\n return negative ? q : away\n case 'floor':\n return negative ? away : q\n default:\n if (twice < d) return q\n if (twice > d) return away\n\n return tie(mode, q, away, negative)\n }\n}\n\n/** The half-way cases of the five `half*` modes. */\nfunction tie(mode: RoundingMode, q: bigint, away: bigint, negative: boolean): bigint {\n if (mode === 'halfExpand') return away\n if (mode === 'halfTrunc') return q\n if (mode === 'halfCeil') return negative ? q : away\n\n if (mode === 'halfFloor') return negative ? away : q\n\n return q % 2n === 0n ? q : away\n}\n\n/** A whole number in `lo..hi`, or a thrown error naming the function and option. */\nexport function wholeIn(fn: string, name: string, value: unknown, lo: number, hi: number): number {\n return typeof value === 'number' && Number.isInteger(value) && value >= lo && value <= hi ? value : badValue(fn, `${name} to be a whole number from ${lo} to ${hi}`, value)\n}\n\n/**\n * A number, decimal string or bigint as a `Scaled`. A number is read by its shortest round-trip text (`0.1` is exactly one\n * tenth, not the binary float nearest to it); `lenient` text may carry a sign, an exponent and so on.\n */\nexport function toScaled(fn: string, what: string, value: unknown): Scaled {\n if (typeof value === 'bigint') return { n: value, s: 0 }\n if (typeof value === 'number') {\n if (!Number.isFinite(value)) return badValue(fn, `${what} to be a finite number`, value)\n\n return readDecimal(fn, Object.is(value, -0) ? '0' : String(value), true)!\n }\n const parsed = typeof value === 'string' ? readDecimal(fn, value, true) : null\n\n return parsed ?? badValue(fn, `${what} to be a number, a decimal string such as \"1.21\" or a bigint`, value, typeof value === 'string' && value.includes(',') ? 'Use a dot as the decimal mark, and no thousands separators.' : typeof value === 'string' && value !== value.trim() ? 'Remove the surrounding spaces.' : '')\n}\n"],"mappings":";;AACA,SAAgB,KAAK,OAAwB;CAC3C,IAAI;EACF,MAAM,OACJ,OAAO,UAAU,WACb,KAAK,UAAU,KAAK,IACpB,OAAO,UAAU,YAAY,UAAU,OACrC,OAAO,UAAU,SAAS,KAAK,KAAK,IACpC,OAAO,UAAU,WACf,GAAG,MAAM,KACT,OAAO,KAAK;EAEtB,OAAO,KAAK,SAAS,KAAK,GAAG,KAAK,MAAM,GAAG,EAAE,EAAE,OAAO;CACxD,QAAQ;EACN,OAAO;CACT;AACF;;AAGA,SAAgB,SAAS,IAAY,UAAkB,KAAc,MAAM,IAAW;CACpF,MAAM,IAAI,UAAU,YAAY,GAAG,aAAa,SAAS,QAAQ,KAAK,GAAG,EAAE,GAAG,QAAQ,KAAK,KAAK,IAAI,OAAO;AAC7G;;AAGA,SAAgB,SAAS,IAAY,SAAwB;CAC3D,MAAM,IAAI,WAAW,YAAY,GAAG,IAAI,SAAS;AACnD;;;;ACXA,MAAa,aAAa;AAK1B,MAAM,QAAQ;CAAC;CAAQ;CAAS;CAAU;CAAS;CAAY;CAAa;CAAc;CAAa;AAA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AO,IAAI,MAAM,GAAG,MAAM,QAAQ;CACtC;AACF;;AAGA,SAAS,IAAI,MAAoB,GAAW,MAAc,UAA2B;CACnF,IAAI,SAAS,cAAc,OAAO;CAClC,IAAI,SAAS,aAAa,OAAO;CACjC,IAAI,SAAS,YAAY,OAAO,WAAW,IAAI;CAE/C,IAAI,SAAS,aAAa,OAAO,WAAW,OAAO;CAEnD,OAAO,IAAI,OAAO,KAAK,IAAI;AAC7B;;AAGA,SAAgB,QAAQ,IAAY,MAAc,OAAgB,IAAY,IAAoB;CAChG,OAAO,OAAO,UAAU,YAAY,OAAO,UAAU,KAAK,KAAK,SAAS,MAAM,SAAS,KAAK,QAAQ,SAAS,IAAI,GAAG,KAAK,6BAA6B,GAAG,MAAM,MAAM,KAAK;AAC5K;;;;;AAMA,SAAgB,SAAS,IAAY,MAAc,OAAwB;CACzE,IAAI,OAAO,UAAU,UAAU,OAAO;EAAE,GAAG;EAAO,GAAG;CAAE;CACvD,IAAI,OAAO,UAAU,UAAU;EAC7B,IAAI,CAAC,OAAO,SAAS,KAAK,GAAG,OAAO,SAAS,IAAI,GAAG,KAAK,yBAAyB,KAAK;EAEvF,OAAO,YAAY,IAAI,OAAO,GAAG,OAAO,EAAE,IAAI,MAAM,OAAO,KAAK,GAAG,IAAI;CACzE;CAGA,QAFe,OAAO,UAAU,WAAW,YAAY,IAAI,OAAO,IAAI,IAAI,SAEzD,SAAS,IAAI,GAAG,KAAK,+DAA+D,OAAO,OAAO,UAAU,YAAY,MAAM,SAAS,GAAG,IAAI,gEAAgE,OAAO,UAAU,YAAY,UAAU,MAAM,KAAK,IAAI,mCAAmC,EAAE;AAC5T"}
package/lib/decimal.js ADDED
@@ -0,0 +1,126 @@
1
+ import { a as pow10, c as wholeIn, i as formatScaled, l as badRange, n as checkMode, o as readDecimal, r as divRound, s as toScaled } from "./_chunks/scaled-eXdrPpWS.js";
2
+
3
+ // src/decimal.ts
4
+ function operand(fn, value) {
5
+ return toScaled(fn, "a decimal", value);
6
+ }
7
+ function align(a, b) {
8
+ if (a.s === b.s) return [
9
+ a.n,
10
+ b.n,
11
+ a.s
12
+ ];
13
+ return a.s > b.s ? [
14
+ a.n,
15
+ b.n * pow10(a.s - b.s),
16
+ a.s
17
+ ] : [
18
+ a.n * pow10(b.s - a.s),
19
+ b.n,
20
+ b.s
21
+ ];
22
+ }
23
+ /**
24
+ * Whether `x` is a canonical decimal string. Never throws.
25
+ *
26
+ * @example isDecimal('9.90') // => true
27
+ * @example isDecimal('.5') // => false
28
+ * @example isDecimal('1e3') // => false
29
+ */
30
+ function isDecimal(x) {
31
+ try {
32
+ return typeof x === "string" && readDecimal("isDecimal", x, false) !== null;
33
+ } catch {
34
+ return false;
35
+ }
36
+ }
37
+ /**
38
+ * The canonical form of a decimal given as text, a number (by its shortest text) or a bigint. The scale is kept: `"1.50"`
39
+ * stays `"1.50"`. Throws on anything that is not a decimal.
40
+ *
41
+ * @example normalize('+.5') // => '0.5'
42
+ * @example normalize('1.5e2') // => '150'
43
+ * @example normalize('-0.00') // => '0.00'
44
+ */
45
+ function normalize(value) {
46
+ const x = operand("normalize", value);
47
+ return formatScaled(x.n, x.s);
48
+ }
49
+ /**
50
+ * Exact sum.
51
+ *
52
+ * @example add('0.1', '0.2') // => '0.3'
53
+ */
54
+ function add(a, b) {
55
+ const [x, y, s] = align(operand("add", a), operand("add", b));
56
+ return formatScaled(x + y, s);
57
+ }
58
+ /**
59
+ * Exact difference.
60
+ *
61
+ * @example subtract('0.3', '0.1') // => '0.2'
62
+ */
63
+ function subtract(a, b) {
64
+ const [x, y, s] = align(operand("subtract", a), operand("subtract", b));
65
+ return formatScaled(x - y, s);
66
+ }
67
+ /**
68
+ * Exact product (the scale is the sum of the scales).
69
+ *
70
+ * @example multiply('19.99', '3') // => '59.97'
71
+ */
72
+ function multiply(a, b) {
73
+ const x = operand("multiply", a);
74
+ const y = operand("multiply", b);
75
+ return formatScaled(x.n * y.n, x.s + y.s);
76
+ }
77
+ /**
78
+ * Quotient rounded to `scale` digits (default 20). A zero divisor throws.
79
+ *
80
+ * @example divide('1', '3', { scale: 4 }) // => '0.3333'
81
+ * @example divide('2', '3', { scale: 2, rounding: 'floor' }) // => '0.66'
82
+ */
83
+ function divide(a, b, options) {
84
+ const x = operand("divide", a);
85
+ const y = operand("divide", b);
86
+ const scale = options?.scale === void 0 ? 20 : wholeIn("divide", "scale", options.scale, 0, 1e3);
87
+ const mode = options?.rounding === void 0 ? "halfExpand" : checkMode("divide", options.rounding);
88
+ if (y.n === 0n) return badRange("divide", `the divisor ${JSON.stringify(String(b))} is zero`);
89
+ return formatScaled(divRound(x.n * pow10(scale + y.s), y.n * pow10(x.s), mode), scale);
90
+ }
91
+ /**
92
+ * -1, 0 or 1.
93
+ *
94
+ * @example compare('9.90', '9.9') // => 0
95
+ * @example compare('-1', '0.5') // => -1
96
+ */
97
+ function compare(a, b) {
98
+ const [x, y] = align(operand("compare", a), operand("compare", b));
99
+ return x < y ? -1 : x > y ? 1 : 0;
100
+ }
101
+ /**
102
+ * Round to `digits` fraction digits (default 0) or to a multiple of `increment`, by `mode` (default `'halfExpand'`, round
103
+ * half away from zero; `'halfEven'` is banker's rounding). The result has the target scale.
104
+ *
105
+ * @example round('2.5') // => '3'
106
+ * @example round('2.5', { mode: 'halfEven' }) // => '2'
107
+ * @example round('1.2345', { digits: 2 }) // => '1.23'
108
+ * @example round('1.23', { increment: '0.05' }) // => '1.25'
109
+ */
110
+ function round(value, options) {
111
+ const x = operand("round", value);
112
+ const mode = options?.mode === void 0 ? "halfExpand" : checkMode("round", options.mode);
113
+ if (options?.increment !== void 0) {
114
+ const inc = operand("round", options.increment);
115
+ if (inc.n <= 0n) return badRange("round", `increment must be greater than zero, got ${JSON.stringify(String(options.increment))}`);
116
+ const s = Math.max(inc.s, options.digits === void 0 ? 0 : wholeIn("round", "digits", options.digits, 0, 1e3), x.s);
117
+ const unit = inc.n * pow10(s - inc.s);
118
+ return formatScaled(divRound(x.n * pow10(s - x.s), unit, mode) * unit, s);
119
+ }
120
+ const digits = options?.digits === void 0 ? 0 : wholeIn("round", "digits", options.digits, 0, 1e3);
121
+ if (digits >= x.s) return formatScaled(x.n * pow10(digits - x.s), digits);
122
+ return formatScaled(divRound(x.n, pow10(x.s - digits), mode), digits);
123
+ }
124
+
125
+ export { add, compare, divide, isDecimal, multiply, normalize, round, subtract };
126
+ //# sourceMappingURL=decimal.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"decimal.js","names":[],"sources":["../src/decimal.ts"],"sourcesContent":["import { badRange } from './errors'\nimport { checkMode, divRound, formatScaled, pow10, readDecimal, type RoundingMode, type Scaled, toScaled, wholeIn } from './scaled'\n\n/**\n * Exact decimals on text: `Decimal` is canonical decimal text (`\"-\"`, digits, optional `\".\" digits`; no exponent, no `+`, no\n * leading zeros, never `-0`). Every operation is exact at any size and returns canonical text; inputs may use the lenient\n * forms `normalize` accepts (`+1.5`, `.5`, `1e-3`). Math runs on `bigint` scaled integers.\n */\nexport type Decimal = string\n\nexport type { RoundingMode }\n\nfunction operand(fn: string, value: unknown): Scaled {\n return toScaled(fn, 'a decimal', value)\n}\n\nfunction align(a: Scaled, b: Scaled): [bigint, bigint, number] {\n if (a.s === b.s) return [a.n, b.n, a.s]\n\n return a.s > b.s ? [a.n, b.n * pow10(a.s - b.s), a.s] : [a.n * pow10(b.s - a.s), b.n, b.s]\n}\n\n/**\n * Whether `x` is a canonical decimal string. Never throws.\n *\n * @example isDecimal('9.90') // => true\n * @example isDecimal('.5') // => false\n * @example isDecimal('1e3') // => false\n */\nexport function isDecimal(x: unknown): x is Decimal {\n try {\n return typeof x === 'string' && readDecimal('isDecimal', x, false) !== null\n } catch {\n return false\n }\n}\n\n/**\n * The canonical form of a decimal given as text, a number (by its shortest text) or a bigint. The scale is kept: `\"1.50\"`\n * stays `\"1.50\"`. Throws on anything that is not a decimal.\n *\n * @example normalize('+.5') // => '0.5'\n * @example normalize('1.5e2') // => '150'\n * @example normalize('-0.00') // => '0.00'\n */\nexport function normalize(value: number | string | bigint): Decimal {\n const x = operand('normalize', value)\n\n return formatScaled(x.n, x.s)\n}\n\n/**\n * Exact sum.\n *\n * @example add('0.1', '0.2') // => '0.3'\n */\nexport function add(a: number | string | bigint, b: number | string | bigint): Decimal {\n const [x, y, s] = align(operand('add', a), operand('add', b))\n\n return formatScaled(x + y, s)\n}\n\n/**\n * Exact difference.\n *\n * @example subtract('0.3', '0.1') // => '0.2'\n */\nexport function subtract(a: number | string | bigint, b: number | string | bigint): Decimal {\n const [x, y, s] = align(operand('subtract', a), operand('subtract', b))\n\n return formatScaled(x - y, s)\n}\n\n/**\n * Exact product (the scale is the sum of the scales).\n *\n * @example multiply('19.99', '3') // => '59.97'\n */\nexport function multiply(a: number | string | bigint, b: number | string | bigint): Decimal {\n const x = operand('multiply', a)\n const y = operand('multiply', b)\n\n return formatScaled(x.n * y.n, x.s + y.s)\n}\n\n/** Options of `divide`. */\nexport interface DivideOptions {\n /** Digits after the decimal point in the result. Default 20. */\n scale?: number\n /** Default `'halfExpand'`. */\n rounding?: RoundingMode\n}\n\n/**\n * Quotient rounded to `scale` digits (default 20). A zero divisor throws.\n *\n * @example divide('1', '3', { scale: 4 }) // => '0.3333'\n * @example divide('2', '3', { scale: 2, rounding: 'floor' }) // => '0.66'\n */\nexport function divide(a: number | string | bigint, b: number | string | bigint, options?: DivideOptions): Decimal {\n const x = operand('divide', a)\n const y = operand('divide', b)\n const scale = options?.scale === undefined ? 20 : wholeIn('divide', 'scale', options.scale, 0, 1000)\n const mode = options?.rounding === undefined ? 'halfExpand' : checkMode('divide', options.rounding)\n\n if (y.n === 0n) return badRange('divide', `the divisor ${JSON.stringify(String(b))} is zero`)\n\n return formatScaled(divRound(x.n * pow10(scale + y.s), y.n * pow10(x.s), mode), scale)\n}\n\n/**\n * -1, 0 or 1.\n *\n * @example compare('9.90', '9.9') // => 0\n * @example compare('-1', '0.5') // => -1\n */\nexport function compare(a: number | string | bigint, b: number | string | bigint): -1 | 0 | 1 {\n const [x, y] = align(operand('compare', a), operand('compare', b))\n\n return x < y ? -1 : x > y ? 1 : 0\n}\n\n/** Options of `round`. */\nexport interface RoundOptions {\n /** Digits after the decimal point to keep. Default 0 (or the increment's scale). */\n digits?: number\n /** Round to a multiple of this decimal instead (`'0.05'` for cash rounding). */\n increment?: number | string\n /** Default `'halfExpand'`. */\n mode?: RoundingMode\n}\n\n/**\n * Round to `digits` fraction digits (default 0) or to a multiple of `increment`, by `mode` (default `'halfExpand'`, round\n * half away from zero; `'halfEven'` is banker's rounding). The result has the target scale.\n *\n * @example round('2.5') // => '3'\n * @example round('2.5', { mode: 'halfEven' }) // => '2'\n * @example round('1.2345', { digits: 2 }) // => '1.23'\n * @example round('1.23', { increment: '0.05' }) // => '1.25'\n */\nexport function round(value: number | string | bigint, options?: RoundOptions): Decimal {\n const x = operand('round', value)\n const mode = options?.mode === undefined ? 'halfExpand' : checkMode('round', options.mode)\n\n if (options?.increment !== undefined) {\n const inc = operand('round', options.increment)\n\n if (inc.n <= 0n) return badRange('round', `increment must be greater than zero, got ${JSON.stringify(String(options.increment))}`)\n const s = Math.max(inc.s, options.digits === undefined ? 0 : wholeIn('round', 'digits', options.digits, 0, 1000), x.s)\n const unit = inc.n * pow10(s - inc.s)\n\n return formatScaled(divRound(x.n * pow10(s - x.s), unit, mode) * unit, s)\n }\n const digits = options?.digits === undefined ? 0 : wholeIn('round', 'digits', options.digits, 0, 1000)\n\n if (digits >= x.s) return formatScaled(x.n * pow10(digits - x.s), digits)\n\n return formatScaled(divRound(x.n, pow10(x.s - digits), mode), digits)\n}\n"],"mappings":";;;AAYA,SAAS,QAAQ,IAAY,OAAwB;CACnD,OAAO,SAAS,IAAI,aAAa,KAAK;AACxC;AAEA,SAAS,MAAM,GAAW,GAAqC;CAC7D,IAAI,EAAE,MAAM,EAAE,GAAG,OAAO;EAAC,EAAE;EAAG,EAAE;EAAG,EAAE;CAAC;CAEtC,OAAO,EAAE,IAAI,EAAE,IAAI;EAAC,EAAE;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,aAAa,SAAS,EAAE,GAAG,MAAM,EAAE,IAAI,MAAM,GAAG,IAAI,GAAG,MAAM;AACtE"}
package/lib/fp.js ADDED
@@ -0,0 +1,91 @@
1
+ import { S as subtract$1, _ as negate, a as convert$1, b as round$1, d as isPositive, f as isZero, g as multiply$1, i as compare, n as add$1, o as divide$1, r as allocate$1, s as equals$1, t as abs, u as isNegative, v as percentage$1, x as split$1 } from "./_chunks/money-B9MhDL2i.js";
2
+
3
+ // src/fp.ts
4
+ /**
5
+ * Value-last forms of the Money operations: each call takes the configuration and returns a plain `(m: Money) => Money`, so an
6
+ * operation can be built once, named, passed to `map` and composed with any `pipe` (`pipe` from `@pyreon/time/fp` or
7
+ * `@pyreon/rx`; this package ships none, so that it has no dependencies). Thin wrappers over the core functions.
8
+ */
9
+ /**
10
+ * `add(b)` is a function that adds `b` to a Money.
11
+ *
12
+ * @example add({ amount: '1.00', currency: 'EUR' })({ amount: '2.50', currency: 'EUR' }) // => { amount: '3.50', currency: 'EUR' }
13
+ */
14
+ function add(b) {
15
+ return (m) => add$1(m, b);
16
+ }
17
+ /**
18
+ * `subtract(b)` subtracts `b`.
19
+ *
20
+ * @example subtract({ amount: '1.00', currency: 'EUR' })({ amount: '2.50', currency: 'EUR' }) // => { amount: '1.50', currency: 'EUR' }
21
+ */
22
+ function subtract(b) {
23
+ return (m) => subtract$1(m, b);
24
+ }
25
+ /**
26
+ * `multiply('1.21')` multiplies by a factor, rounded to the currency's digits.
27
+ *
28
+ * @example multiply('1.21')({ amount: '10.00', currency: 'EUR' }) // => { amount: '12.10', currency: 'EUR' }
29
+ */
30
+ function multiply(factor, options) {
31
+ return (m) => multiply$1(m, factor, options);
32
+ }
33
+ /**
34
+ * `divide(3)` divides, rounded to the currency's digits.
35
+ *
36
+ * @example divide(3)({ amount: '10.00', currency: 'EUR' }) // => { amount: '3.33', currency: 'EUR' }
37
+ */
38
+ function divide(divisor, options) {
39
+ return (m) => divide$1(m, divisor, options);
40
+ }
41
+ /**
42
+ * `percentage(21)` takes 21 percent.
43
+ *
44
+ * @example percentage(21)({ amount: '200.00', currency: 'EUR' }) // => { amount: '42.00', currency: 'EUR' }
45
+ */
46
+ function percentage(percent, options) {
47
+ return (m) => percentage$1(m, percent, options);
48
+ }
49
+ /**
50
+ * `round({ increment: '0.05' })` rounds (cash rounding, fewer digits, any mode).
51
+ *
52
+ * @example round({ increment: '0.05' })({ amount: '1.23', currency: 'CHF' }) // => { amount: '1.25', currency: 'CHF' }
53
+ */
54
+ function round(options) {
55
+ return (m) => round$1(m, options);
56
+ }
57
+ /**
58
+ * `convert('USD', '1.0842')` converts with a rate.
59
+ *
60
+ * @example convert('USD', '1.0842')({ amount: '100.00', currency: 'EUR' }) // => { amount: '108.42', currency: 'USD' }
61
+ */
62
+ function convert(to, rate, options) {
63
+ return (m) => convert$1(m, to, rate, options);
64
+ }
65
+ /**
66
+ * `allocate([1, 1, 1])` shares an amount into parts that sum exactly to it.
67
+ *
68
+ * @example allocate([1, 1, 1])({ amount: '100.00', currency: 'EUR' }).map((p) => p.amount) // => ['33.34', '33.33', '33.33']
69
+ */
70
+ function allocate(ratios) {
71
+ return (m) => allocate$1(m, ratios);
72
+ }
73
+ /**
74
+ * `split(3)` splits into equal parts that sum exactly to the amount.
75
+ *
76
+ * @example split(2)({ amount: '0.01', currency: 'EUR' }).map((p) => p.amount) // => ['0.01', '0.00']
77
+ */
78
+ function split(parts) {
79
+ return (m) => split$1(m, parts);
80
+ }
81
+ /**
82
+ * `equals(other)` is a predicate: true for an amount equal to `other`.
83
+ *
84
+ * @example equals({ amount: '1.00', currency: 'EUR' })({ amount: '1.00', currency: 'EUR' }) // => true
85
+ */
86
+ function equals(other) {
87
+ return (m) => equals$1(m, other);
88
+ }
89
+
90
+ export { abs, add, allocate, compare, convert, divide, equals, isNegative, isPositive, isZero, multiply, negate, percentage, round, split, subtract };
91
+ //# sourceMappingURL=fp.js.map
package/lib/fp.js.map ADDED
@@ -0,0 +1 @@
1
+ {"version":3,"file":"fp.js","names":["core.add","core.subtract","core.multiply","core.divide","core.percentage","core.round","core.convert","core.allocate","core.split","core.equals"],"sources":["../src/fp.ts"],"sourcesContent":["import type { CurrencyCode } from './currency'\nimport * as core from './money'\nimport type { Money, MoneyRoundOptions, RoundingOptions } from './money'\n\n/**\n * Value-last forms of the Money operations: each call takes the configuration and returns a plain `(m: Money) => Money`, so an\n * operation can be built once, named, passed to `map` and composed with any `pipe` (`pipe` from `@pyreon/time/fp` or\n * `@pyreon/rx`; this package ships none, so that it has no dependencies). Thin wrappers over the core functions.\n */\n\n/**\n * `add(b)` is a function that adds `b` to a Money.\n *\n * @example add({ amount: '1.00', currency: 'EUR' })({ amount: '2.50', currency: 'EUR' }) // => { amount: '3.50', currency: 'EUR' }\n */\nexport function add(b: Money): (m: Money) => Money {\n return (m) => core.add(m, b)\n}\n\n/**\n * `subtract(b)` subtracts `b`.\n *\n * @example subtract({ amount: '1.00', currency: 'EUR' })({ amount: '2.50', currency: 'EUR' }) // => { amount: '1.50', currency: 'EUR' }\n */\nexport function subtract(b: Money): (m: Money) => Money {\n return (m) => core.subtract(m, b)\n}\n\n/**\n * `multiply('1.21')` multiplies by a factor, rounded to the currency's digits.\n *\n * @example multiply('1.21')({ amount: '10.00', currency: 'EUR' }) // => { amount: '12.10', currency: 'EUR' }\n */\nexport function multiply(factor: number | string | bigint, options?: RoundingOptions): (m: Money) => Money {\n return (m) => core.multiply(m, factor, options)\n}\n\n/**\n * `divide(3)` divides, rounded to the currency's digits.\n *\n * @example divide(3)({ amount: '10.00', currency: 'EUR' }) // => { amount: '3.33', currency: 'EUR' }\n */\nexport function divide(divisor: number | string | bigint, options?: RoundingOptions): (m: Money) => Money {\n return (m) => core.divide(m, divisor, options)\n}\n\n/**\n * `percentage(21)` takes 21 percent.\n *\n * @example percentage(21)({ amount: '200.00', currency: 'EUR' }) // => { amount: '42.00', currency: 'EUR' }\n */\nexport function percentage(percent: number | string | bigint, options?: RoundingOptions): (m: Money) => Money {\n return (m) => core.percentage(m, percent, options)\n}\n\n/**\n * `round({ increment: '0.05' })` rounds (cash rounding, fewer digits, any mode).\n *\n * @example round({ increment: '0.05' })({ amount: '1.23', currency: 'CHF' }) // => { amount: '1.25', currency: 'CHF' }\n */\nexport function round(options?: MoneyRoundOptions): (m: Money) => Money {\n return (m) => core.round(m, options)\n}\n\n/**\n * `convert('USD', '1.0842')` converts with a rate.\n *\n * @example convert('USD', '1.0842')({ amount: '100.00', currency: 'EUR' }) // => { amount: '108.42', currency: 'USD' }\n */\nexport function convert(to: CurrencyCode, rate: number | string | bigint, options?: RoundingOptions): (m: Money) => Money {\n return (m) => core.convert(m, to, rate, options)\n}\n\n/**\n * `allocate([1, 1, 1])` shares an amount into parts that sum exactly to it.\n *\n * @example allocate([1, 1, 1])({ amount: '100.00', currency: 'EUR' }).map((p) => p.amount) // => ['33.34', '33.33', '33.33']\n */\nexport function allocate(ratios: readonly (number | string)[]): (m: Money) => Money[] {\n return (m) => core.allocate(m, ratios)\n}\n\n/**\n * `split(3)` splits into equal parts that sum exactly to the amount.\n *\n * @example split(2)({ amount: '0.01', currency: 'EUR' }).map((p) => p.amount) // => ['0.01', '0.00']\n */\nexport function split(parts: number): (m: Money) => Money[] {\n return (m) => core.split(m, parts)\n}\n\n/**\n * `equals(other)` is a predicate: true for an amount equal to `other`.\n *\n * @example equals({ amount: '1.00', currency: 'EUR' })({ amount: '1.00', currency: 'EUR' }) // => true\n */\nexport function equals(other: Money): (m: Money) => boolean {\n return (m) => core.equals(m, other)\n}\n\n// Operations that already take one value are the same function in both entries.\nexport { abs, compare, isNegative, isPositive, isZero, negate } from './money'\nexport type { Money, MoneyRoundOptions, RoundingOptions } from './money'\n"],"mappings":";;;;;;;;;;;;;AAeA,SAAgB,IAAI,GAA+B;CACjD,QAAQ,MAAMA,MAAS,GAAG,CAAC;AAC7B;;;;;;AAOA,SAAgB,SAAS,GAA+B;CACtD,QAAQ,MAAMC,WAAc,GAAG,CAAC;AAClC;;;;;;AAOA,SAAgB,SAAS,QAAkC,SAAgD;CACzG,QAAQ,MAAMC,WAAc,GAAG,QAAQ,OAAO;AAChD;;;;;;AAOA,SAAgB,OAAO,SAAmC,SAAgD;CACxG,QAAQ,MAAMC,SAAY,GAAG,SAAS,OAAO;AAC/C;;;;;;AAOA,SAAgB,WAAW,SAAmC,SAAgD;CAC5G,QAAQ,MAAMC,aAAgB,GAAG,SAAS,OAAO;AACnD;;;;;;AAOA,SAAgB,MAAM,SAAkD;CACtE,QAAQ,MAAMC,QAAW,GAAG,OAAO;AACrC;;;;;;AAOA,SAAgB,QAAQ,IAAkB,MAAgC,SAAgD;CACxH,QAAQ,MAAMC,UAAa,GAAG,IAAI,MAAM,OAAO;AACjD;;;;;;AAOA,SAAgB,SAAS,QAA6D;CACpF,QAAQ,MAAMC,WAAc,GAAG,MAAM;AACvC;;;;;;AAOA,SAAgB,MAAM,OAAsC;CAC1D,QAAQ,MAAMC,QAAW,GAAG,KAAK;AACnC;;;;;;AAOA,SAAgB,OAAO,OAAqC;CAC1D,QAAQ,MAAMC,SAAY,GAAG,KAAK;AACpC"}
package/lib/index.js ADDED
@@ -0,0 +1,3 @@
1
+ import { C as sum, D as currencyDigits, E as zero, O as defineCurrency, S as subtract, T as toMinorNumber, _ as negate, a as convert, b as round, c as fromMinor, d as isPositive, f as isZero, g as multiply, h as money, i as compare, k as isCurrency, l as isMoney, m as min, n as add, o as divide, p as max, r as allocate, s as equals, t as abs, u as isNegative, v as percentage, w as toMinor, x as split, y as ratio } from "./_chunks/money-B9MhDL2i.js";
2
+
3
+ export { abs, add, allocate, compare, convert, currencyDigits, defineCurrency, divide, equals, fromMinor, isCurrency, isMoney, isNegative, isPositive, isZero, max, min, money, multiply, negate, percentage, ratio, round, split, subtract, sum, toMinor, toMinorNumber, zero };