Spaces:
Sleeping
Sleeping
Commit ·
5918e23
1
Parent(s): d180c31
fix(domain): guard split allocation and balance invariants
Browse files- src/lib/domain/balances.ts +6 -1
- src/lib/domain/money.ts +4 -2
- src/lib/domain/schemas.ts +22 -16
- src/lib/domain/split.ts +7 -10
- tests/unit/domain/balances.test.ts +54 -2
- tests/unit/domain/schemas.test.ts +10 -1
- tests/unit/domain/split.test.ts +64 -3
src/lib/domain/balances.ts
CHANGED
|
@@ -24,8 +24,13 @@ export function computeNets(expenses: Iterable<Expense>, settlements: Iterable<S
|
|
| 24 |
const byMagnitudeThenId = (a: [string, number], b: [string, number]) =>
|
| 25 |
Math.abs(b[1]) - Math.abs(a[1]) || (a[0] < b[0] ? -1 : a[0] > b[0] ? 1 : 0);
|
| 26 |
|
| 27 |
-
/**
|
|
|
|
|
|
|
|
|
|
| 28 |
export function simplifyDebts(nets: Map<string, number>): Debt[] {
|
|
|
|
|
|
|
| 29 |
const creditors = [...nets].filter(([, v]) => v > 0).sort(byMagnitudeThenId);
|
| 30 |
const debtors = [...nets]
|
| 31 |
.filter(([, v]) => v < 0)
|
|
|
|
| 24 |
const byMagnitudeThenId = (a: [string, number], b: [string, number]) =>
|
| 25 |
Math.abs(b[1]) - Math.abs(a[1]) || (a[0] < b[0] ? -1 : a[0] > b[0] ? 1 : 0);
|
| 26 |
|
| 27 |
+
/**
|
| 28 |
+
* Greedy pairing of largest debtor with largest creditor. Deterministic; at most n-1 transfers.
|
| 29 |
+
* Precondition: nets must sum to zero.
|
| 30 |
+
*/
|
| 31 |
export function simplifyDebts(nets: Map<string, number>): Debt[] {
|
| 32 |
+
const total = [...nets.values()].reduce((a, b) => a + b, 0);
|
| 33 |
+
if (total !== 0) throw new Error(`Balances do not sum to zero (got ${total})`);
|
| 34 |
const creditors = [...nets].filter(([, v]) => v > 0).sort(byMagnitudeThenId);
|
| 35 |
const debtors = [...nets]
|
| 36 |
.filter(([, v]) => v < 0)
|
src/lib/domain/money.ts
CHANGED
|
@@ -1,13 +1,15 @@
|
|
|
|
|
|
|
|
| 1 |
const AMOUNT_RE = /^(\d{1,3}(?:,\d{3})*|\d+)(?:\.(\d{1,2}))?$/;
|
| 2 |
|
| 3 |
-
/** "12.34" -> 1234. Accepts thousands separators. Returns null for anything invalid
|
| 4 |
export function parseAmountToCents(input: string): number | null {
|
| 5 |
const m = AMOUNT_RE.exec(input.trim());
|
| 6 |
if (!m) return null;
|
| 7 |
const whole = Number(m[1].replace(/,/g, ''));
|
| 8 |
const frac = (m[2] ?? '').padEnd(2, '0');
|
| 9 |
const cents = whole * 100 + Number(frac);
|
| 10 |
-
if (!Number.isSafeInteger(cents) || cents <= 0) return null;
|
| 11 |
return cents;
|
| 12 |
}
|
| 13 |
|
|
|
|
| 1 |
+
import { MAX_CENTS } from './schemas';
|
| 2 |
+
|
| 3 |
const AMOUNT_RE = /^(\d{1,3}(?:,\d{3})*|\d+)(?:\.(\d{1,2}))?$/;
|
| 4 |
|
| 5 |
+
/** "12.34" -> 1234. Accepts thousands separators. Returns null for anything invalid, non-positive, or over MAX_CENTS. */
|
| 6 |
export function parseAmountToCents(input: string): number | null {
|
| 7 |
const m = AMOUNT_RE.exec(input.trim());
|
| 8 |
if (!m) return null;
|
| 9 |
const whole = Number(m[1].replace(/,/g, ''));
|
| 10 |
const frac = (m[2] ?? '').padEnd(2, '0');
|
| 11 |
const cents = whole * 100 + Number(frac);
|
| 12 |
+
if (!Number.isSafeInteger(cents) || cents <= 0 || cents > MAX_CENTS) return null;
|
| 13 |
return cents;
|
| 14 |
}
|
| 15 |
|
src/lib/domain/schemas.ts
CHANGED
|
@@ -12,8 +12,9 @@ export function isValidDate(s: string): boolean {
|
|
| 12 |
|
| 13 |
export const DateString = z.string().refine(isValidDate, 'Invalid date');
|
| 14 |
export const IsoTimestamp = z.iso.datetime();
|
| 15 |
-
export const
|
| 16 |
-
export const
|
|
|
|
| 17 |
export const UserId = z.string().min(1);
|
| 18 |
|
| 19 |
export const UserSchema = z.object({
|
|
@@ -57,20 +58,25 @@ export const ExpensePhotoSchema = z.object({
|
|
| 57 |
height: z.number().int().positive().optional()
|
| 58 |
});
|
| 59 |
|
| 60 |
-
export const ExpenseSchema = z
|
| 61 |
-
|
| 62 |
-
|
| 63 |
-
|
| 64 |
-
|
| 65 |
-
|
| 66 |
-
|
| 67 |
-
|
| 68 |
-
|
| 69 |
-
|
| 70 |
-
|
| 71 |
-
|
| 72 |
-
|
| 73 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 74 |
|
| 75 |
export const SettlementSchema = z
|
| 76 |
.object({
|
|
|
|
| 12 |
|
| 13 |
export const DateString = z.string().refine(isValidDate, 'Invalid date');
|
| 14 |
export const IsoTimestamp = z.iso.datetime();
|
| 15 |
+
export const MAX_CENTS = 100_000_000_000;
|
| 16 |
+
export const Cents = z.number().int().positive().max(MAX_CENTS);
|
| 17 |
+
export const NonNegCents = z.number().int().nonnegative().max(MAX_CENTS);
|
| 18 |
export const UserId = z.string().min(1);
|
| 19 |
|
| 20 |
export const UserSchema = z.object({
|
|
|
|
| 58 |
height: z.number().int().positive().optional()
|
| 59 |
});
|
| 60 |
|
| 61 |
+
export const ExpenseSchema = z
|
| 62 |
+
.object({
|
| 63 |
+
id: z.string().min(1),
|
| 64 |
+
version: z.number().int().positive(),
|
| 65 |
+
description: z.string().trim().min(1).max(120),
|
| 66 |
+
amountCents: Cents,
|
| 67 |
+
currency: z.string().regex(/^[A-Z]{3}$/),
|
| 68 |
+
date: DateString,
|
| 69 |
+
paidBy: UserId,
|
| 70 |
+
split: SplitSchema,
|
| 71 |
+
shares: z.record(UserId, NonNegCents),
|
| 72 |
+
photo: ExpensePhotoSchema.optional(),
|
| 73 |
+
notes: z.string().max(2000).optional(),
|
| 74 |
+
...AuditShape
|
| 75 |
+
})
|
| 76 |
+
.refine((e) => Object.values(e.shares).reduce((a, b) => a + b, 0) === e.amountCents, {
|
| 77 |
+
message: 'shares must add up to amountCents',
|
| 78 |
+
path: ['shares']
|
| 79 |
+
});
|
| 80 |
|
| 81 |
export const SettlementSchema = z
|
| 82 |
.object({
|
src/lib/domain/split.ts
CHANGED
|
@@ -33,20 +33,16 @@ export function allocate(total: number, weights: Weighted[]): Record<string, num
|
|
| 33 |
|
| 34 |
const rows = weights.map((w) => {
|
| 35 |
const scaled = total * w.weight;
|
|
|
|
| 36 |
const floor = Math.floor(scaled / sumW);
|
| 37 |
return { id: w.id, floor, remainder: scaled - floor * sumW };
|
| 38 |
});
|
| 39 |
|
| 40 |
-
|
|
|
|
| 41 |
const order = [...rows].sort((x, y) => y.remainder - x.remainder || (x.id < y.id ? -1 : x.id > y.id ? 1 : 0));
|
| 42 |
-
|
| 43 |
-
|
| 44 |
-
for (const r of order) {
|
| 45 |
-
if (leftover === 0) break;
|
| 46 |
-
result[r.id] += 1;
|
| 47 |
-
leftover -= 1;
|
| 48 |
-
}
|
| 49 |
-
return result;
|
| 50 |
}
|
| 51 |
|
| 52 |
/** Resolves a Split into per-participant integer cents that sum exactly to amountCents. */
|
|
@@ -59,8 +55,8 @@ export function resolveShares(amountCents: number, split: Split): Record<string,
|
|
| 59 |
);
|
| 60 |
case 'percent': {
|
| 61 |
const entries = Object.entries(split.bp);
|
| 62 |
-
const total = entries.reduce((acc, [, bp]) => acc + bp, 0);
|
| 63 |
if (entries.length === 0) throw new SplitError('At least one participant is required', 'participants');
|
|
|
|
| 64 |
if (total !== 10000) throw new SplitError(`Percentages must add up to 100% (got ${(total / 100).toFixed(2)}%)`, 'shares');
|
| 65 |
return allocate(
|
| 66 |
amountCents,
|
|
@@ -70,6 +66,7 @@ export function resolveShares(amountCents: number, split: Split): Record<string,
|
|
| 70 |
case 'exact': {
|
| 71 |
const entries = Object.entries(split.cents);
|
| 72 |
if (entries.length === 0) throw new SplitError('At least one participant is required', 'participants');
|
|
|
|
| 73 |
const total = entries.reduce((acc, [, c]) => acc + c, 0);
|
| 74 |
for (const [id, c] of entries) {
|
| 75 |
if (!Number.isSafeInteger(c) || c <= 0) throw new SplitError(`Amount for ${id} must be positive`, 'shares');
|
|
|
|
| 33 |
|
| 34 |
const rows = weights.map((w) => {
|
| 35 |
const scaled = total * w.weight;
|
| 36 |
+
if (!Number.isSafeInteger(scaled)) throw new SplitError('Amount too large to split precisely', 'amount');
|
| 37 |
const floor = Math.floor(scaled / sumW);
|
| 38 |
return { id: w.id, floor, remainder: scaled - floor * sumW };
|
| 39 |
});
|
| 40 |
|
| 41 |
+
const leftover = total - rows.reduce((acc, r) => acc + r.floor, 0);
|
| 42 |
+
if (leftover < 0 || leftover >= rows.length) throw new SplitError('Internal allocation error', 'amount');
|
| 43 |
const order = [...rows].sort((x, y) => y.remainder - x.remainder || (x.id < y.id ? -1 : x.id > y.id ? 1 : 0));
|
| 44 |
+
for (let k = 0; k < leftover; k++) order[k].floor += 1;
|
| 45 |
+
return Object.fromEntries(rows.map((r) => [r.id, r.floor]));
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 46 |
}
|
| 47 |
|
| 48 |
/** Resolves a Split into per-participant integer cents that sum exactly to amountCents. */
|
|
|
|
| 55 |
);
|
| 56 |
case 'percent': {
|
| 57 |
const entries = Object.entries(split.bp);
|
|
|
|
| 58 |
if (entries.length === 0) throw new SplitError('At least one participant is required', 'participants');
|
| 59 |
+
const total = entries.reduce((acc, [, bp]) => acc + bp, 0);
|
| 60 |
if (total !== 10000) throw new SplitError(`Percentages must add up to 100% (got ${(total / 100).toFixed(2)}%)`, 'shares');
|
| 61 |
return allocate(
|
| 62 |
amountCents,
|
|
|
|
| 66 |
case 'exact': {
|
| 67 |
const entries = Object.entries(split.cents);
|
| 68 |
if (entries.length === 0) throw new SplitError('At least one participant is required', 'participants');
|
| 69 |
+
if (!Number.isSafeInteger(amountCents) || amountCents <= 0) throw new SplitError('Total must be a positive integer', 'amount');
|
| 70 |
const total = entries.reduce((acc, [, c]) => acc + c, 0);
|
| 71 |
for (const [id, c] of entries) {
|
| 72 |
if (!Number.isSafeInteger(c) || c <= 0) throw new SplitError(`Amount for ${id} must be positive`, 'shares');
|
tests/unit/domain/balances.test.ts
CHANGED
|
@@ -2,13 +2,23 @@ import { describe, expect, it } from 'vitest';
|
|
| 2 |
import { computeNets, simplifyDebts } from '../../../src/lib/domain/balances';
|
| 3 |
import type { Expense, Settlement } from '../../../src/lib/domain/types';
|
| 4 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 5 |
const audit = { createdBy: 'a', createdAt: '2026-01-01T00:00:00.000Z', updatedBy: 'a', updatedAt: '2026-01-01T00:00:00.000Z' };
|
|
|
|
| 6 |
const exp = (paidBy: string, amountCents: number, shares: Record<string, number>): Expense => ({
|
| 7 |
-
id: `e_${
|
| 8 |
paidBy, split: { mode: 'exact', cents: shares }, shares, ...audit
|
| 9 |
});
|
| 10 |
const pay = (from: string, to: string, amountCents: number): Settlement => ({
|
| 11 |
-
id: `s_${
|
| 12 |
});
|
| 13 |
|
| 14 |
describe('computeNets', () => {
|
|
@@ -23,6 +33,11 @@ describe('computeNets', () => {
|
|
| 23 |
expect(nets.get('b')).toBe(0);
|
| 24 |
});
|
| 25 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 26 |
it('nets always sum to zero (property)', () => {
|
| 27 |
const nets = computeNets(
|
| 28 |
[exp('a', 1001, { a: 334, b: 333, c: 334 }), exp('b', 77, { c: 77 }), exp('c', 5, { a: 2, b: 3 })],
|
|
@@ -54,4 +69,41 @@ describe('simplifyDebts', () => {
|
|
| 54 |
const nets = new Map([['b', -100], ['a', 100], ['c', -50], ['d', 50]]);
|
| 55 |
expect(simplifyDebts(nets)).toEqual(simplifyDebts(new Map([...nets].reverse())));
|
| 56 |
});
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 57 |
});
|
|
|
|
| 2 |
import { computeNets, simplifyDebts } from '../../../src/lib/domain/balances';
|
| 3 |
import type { Expense, Settlement } from '../../../src/lib/domain/types';
|
| 4 |
|
| 5 |
+
function mulberry32(seed: number) {
|
| 6 |
+
return () => {
|
| 7 |
+
seed = (seed + 0x6d2b79f5) | 0;
|
| 8 |
+
let t = Math.imul(seed ^ (seed >>> 15), 1 | seed);
|
| 9 |
+
t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t;
|
| 10 |
+
return ((t ^ (t >>> 14)) >>> 0) / 4294967296;
|
| 11 |
+
};
|
| 12 |
+
}
|
| 13 |
+
|
| 14 |
const audit = { createdBy: 'a', createdAt: '2026-01-01T00:00:00.000Z', updatedBy: 'a', updatedAt: '2026-01-01T00:00:00.000Z' };
|
| 15 |
+
let idCounter = 0;
|
| 16 |
const exp = (paidBy: string, amountCents: number, shares: Record<string, number>): Expense => ({
|
| 17 |
+
id: `e_${idCounter++}`, version: 1, description: 'x', amountCents, currency: 'USD', date: '2026-01-01',
|
| 18 |
paidBy, split: { mode: 'exact', cents: shares }, shares, ...audit
|
| 19 |
});
|
| 20 |
const pay = (from: string, to: string, amountCents: number): Settlement => ({
|
| 21 |
+
id: `s_${idCounter++}`, version: 1, from, to, amountCents, date: '2026-01-01', ...audit
|
| 22 |
});
|
| 23 |
|
| 24 |
describe('computeNets', () => {
|
|
|
|
| 33 |
expect(nets.get('b')).toBe(0);
|
| 34 |
});
|
| 35 |
|
| 36 |
+
it('handles settlement-only users', () => {
|
| 37 |
+
const nets = computeNets([], [pay('x', 'y', 5)]);
|
| 38 |
+
expect(nets).toEqual(new Map([['x', 5], ['y', -5]]));
|
| 39 |
+
});
|
| 40 |
+
|
| 41 |
it('nets always sum to zero (property)', () => {
|
| 42 |
const nets = computeNets(
|
| 43 |
[exp('a', 1001, { a: 334, b: 333, c: 334 }), exp('b', 77, { c: 77 }), exp('c', 5, { a: 2, b: 3 })],
|
|
|
|
| 69 |
const nets = new Map([['b', -100], ['a', 100], ['c', -50], ['d', 50]]);
|
| 70 |
expect(simplifyDebts(nets)).toEqual(simplifyDebts(new Map([...nets].reverse())));
|
| 71 |
});
|
| 72 |
+
|
| 73 |
+
it('breaks debtor ties by ascending id', () => {
|
| 74 |
+
const nets = new Map([['z', -100], ['a', -100], ['m', 200]]);
|
| 75 |
+
expect(simplifyDebts(nets)).toEqual([
|
| 76 |
+
{ from: 'a', to: 'm', cents: 100 },
|
| 77 |
+
{ from: 'z', to: 'm', cents: 100 }
|
| 78 |
+
]);
|
| 79 |
+
});
|
| 80 |
+
|
| 81 |
+
it('throws when nets do not sum to zero', () => {
|
| 82 |
+
expect(() => simplifyDebts(new Map([['a', 100], ['b', -50]]))).toThrow();
|
| 83 |
+
});
|
| 84 |
+
|
| 85 |
+
it('never needs more than n-1 transfers for random balanced maps (property)', () => {
|
| 86 |
+
const rnd = mulberry32(7);
|
| 87 |
+
for (let iter = 0; iter < 200; iter++) {
|
| 88 |
+
const n = 2 + Math.floor(rnd() * 8);
|
| 89 |
+
const ids = Array.from({ length: n }, (_, k) => `u${k}`);
|
| 90 |
+
const nets = new Map<string, number>();
|
| 91 |
+
let total = 0;
|
| 92 |
+
for (let k = 0; k < n - 1; k++) {
|
| 93 |
+
const v = Math.floor(rnd() * 2001) - 1000;
|
| 94 |
+
nets.set(ids[k], v);
|
| 95 |
+
total += v;
|
| 96 |
+
}
|
| 97 |
+
nets.set(ids[n - 1], -total);
|
| 98 |
+
|
| 99 |
+
const debts = simplifyDebts(nets);
|
| 100 |
+
expect(debts.length).toBeLessThanOrEqual(n - 1);
|
| 101 |
+
const after = new Map(nets);
|
| 102 |
+
for (const d of debts) {
|
| 103 |
+
after.set(d.from, (after.get(d.from) ?? 0) + d.cents);
|
| 104 |
+
after.set(d.to, (after.get(d.to) ?? 0) - d.cents);
|
| 105 |
+
}
|
| 106 |
+
expect([...after.values()].every((v) => v === 0)).toBe(true);
|
| 107 |
+
}
|
| 108 |
+
});
|
| 109 |
});
|
tests/unit/domain/schemas.test.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
| 1 |
import { describe, expect, it } from 'vitest';
|
| 2 |
-
import { ExpenseSchema, IsoTimestamp, SettlementSchema, UserSchema } from '../../../src/lib/domain/schemas';
|
| 3 |
|
| 4 |
const baseExpense = {
|
| 5 |
id: 'e_01HZX',
|
|
@@ -52,6 +52,15 @@ describe('ExpenseSchema', () => {
|
|
| 52 |
};
|
| 53 |
expect(ExpenseSchema.safeParse(oneCentSplitTwoWays).success).toBe(true);
|
| 54 |
});
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 55 |
});
|
| 56 |
|
| 57 |
describe('IsoTimestamp', () => {
|
|
|
|
| 1 |
import { describe, expect, it } from 'vitest';
|
| 2 |
+
import { ExpenseSchema, IsoTimestamp, MAX_CENTS, SettlementSchema, UserSchema } from '../../../src/lib/domain/schemas';
|
| 3 |
|
| 4 |
const baseExpense = {
|
| 5 |
id: 'e_01HZX',
|
|
|
|
| 52 |
};
|
| 53 |
expect(ExpenseSchema.safeParse(oneCentSplitTwoWays).success).toBe(true);
|
| 54 |
});
|
| 55 |
+
|
| 56 |
+
it('rejects shares that do not sum to amountCents', () => {
|
| 57 |
+
const bad = { ...baseExpense, shares: { u_a: 1000, u_b: 1500 } };
|
| 58 |
+
expect(ExpenseSchema.safeParse(bad).success).toBe(false);
|
| 59 |
+
});
|
| 60 |
+
|
| 61 |
+
it('rejects amountCents above MAX_CENTS', () => {
|
| 62 |
+
expect(ExpenseSchema.safeParse({ ...baseExpense, amountCents: MAX_CENTS + 1 }).success).toBe(false);
|
| 63 |
+
});
|
| 64 |
});
|
| 65 |
|
| 66 |
describe('IsoTimestamp', () => {
|
tests/unit/domain/split.test.ts
CHANGED
|
@@ -3,6 +3,25 @@ import { allocate, resolveShares, SplitError } from '../../../src/lib/domain/spl
|
|
| 3 |
|
| 4 |
const sum = (r: Record<string, number>) => Object.values(r).reduce((a, b) => a + b, 0);
|
| 5 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 6 |
describe('allocate', () => {
|
| 7 |
it('splits evenly when divisible', () => {
|
| 8 |
expect(allocate(3000, [{ id: 'a', weight: 1 }, { id: 'b', weight: 1 }, { id: 'c', weight: 1 }])).toEqual({ a: 1000, b: 1000, c: 1000 });
|
|
@@ -19,9 +38,41 @@ describe('allocate', () => {
|
|
| 19 |
expect(allocate(100, [{ id: 'a', weight: 1 }, { id: 'b', weight: 2 }])).toEqual({ a: 33, b: 67 });
|
| 20 |
});
|
| 21 |
|
| 22 |
-
it('
|
| 23 |
-
|
| 24 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 25 |
for (let i = 0; i < 500; i++) {
|
| 26 |
const n = 1 + Math.floor(rnd() * 8);
|
| 27 |
const total = 1 + Math.floor(rnd() * 1_000_000);
|
|
@@ -30,6 +81,9 @@ describe('allocate', () => {
|
|
| 30 |
expect(sum(r)).toBe(total);
|
| 31 |
expect(Object.keys(r)).toHaveLength(n);
|
| 32 |
expect(Object.values(r).every((v) => v >= 0)).toBe(true);
|
|
|
|
|
|
|
|
|
|
| 33 |
}
|
| 34 |
});
|
| 35 |
});
|
|
@@ -49,6 +103,13 @@ describe('resolveShares', () => {
|
|
| 49 |
expect(() => resolveShares(1000, { mode: 'exact', cents: { a: 1, b: 998 } })).toThrow(SplitError);
|
| 50 |
});
|
| 51 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 52 |
it('rejects empty or duplicate participants', () => {
|
| 53 |
expect(() => resolveShares(1000, { mode: 'equal', participants: [] })).toThrow(SplitError);
|
| 54 |
expect(() => resolveShares(1000, { mode: 'equal', participants: ['a', 'a'] })).toThrow(SplitError);
|
|
|
|
| 3 |
|
| 4 |
const sum = (r: Record<string, number>) => Object.values(r).reduce((a, b) => a + b, 0);
|
| 5 |
|
| 6 |
+
function mulberry32(seed: number) {
|
| 7 |
+
return () => {
|
| 8 |
+
seed = (seed + 0x6d2b79f5) | 0;
|
| 9 |
+
let t = Math.imul(seed ^ (seed >>> 15), 1 | seed);
|
| 10 |
+
t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t;
|
| 11 |
+
return ((t ^ (t >>> 14)) >>> 0) / 4294967296;
|
| 12 |
+
};
|
| 13 |
+
}
|
| 14 |
+
|
| 15 |
+
function fieldOf(fn: () => unknown): string {
|
| 16 |
+
try {
|
| 17 |
+
fn();
|
| 18 |
+
} catch (e) {
|
| 19 |
+
if (e instanceof SplitError) return e.field;
|
| 20 |
+
throw e;
|
| 21 |
+
}
|
| 22 |
+
throw new Error('expected to throw');
|
| 23 |
+
}
|
| 24 |
+
|
| 25 |
describe('allocate', () => {
|
| 26 |
it('splits evenly when divisible', () => {
|
| 27 |
expect(allocate(3000, [{ id: 'a', weight: 1 }, { id: 'b', weight: 1 }, { id: 'c', weight: 1 }])).toEqual({ a: 1000, b: 1000, c: 1000 });
|
|
|
|
| 38 |
expect(allocate(100, [{ id: 'a', weight: 1 }, { id: 'b', weight: 2 }])).toEqual({ a: 33, b: 67 });
|
| 39 |
});
|
| 40 |
|
| 41 |
+
it('gives leftover cents to the earliest id when the total is smaller than the participant count', () => {
|
| 42 |
+
expect(allocate(1, [{ id: 'a', weight: 1 }, { id: 'b', weight: 1 }, { id: 'c', weight: 1 }])).toEqual({ a: 1, b: 0, c: 0 });
|
| 43 |
+
});
|
| 44 |
+
|
| 45 |
+
it('gives the whole total to a single participant', () => {
|
| 46 |
+
expect(allocate(500, [{ id: 'a', weight: 1 }])).toEqual({ a: 500 });
|
| 47 |
+
});
|
| 48 |
+
|
| 49 |
+
it('supports a participant id of "__proto__"', () => {
|
| 50 |
+
const r = allocate(100, [{ id: '__proto__', weight: 1 }, { id: 'b', weight: 1 }, { id: 'c', weight: 1 }]);
|
| 51 |
+
expect(Object.keys(r)).toHaveLength(3);
|
| 52 |
+
expect(sum(r)).toBe(100);
|
| 53 |
+
});
|
| 54 |
+
|
| 55 |
+
it('rejects a non-positive total with field "amount"', () => {
|
| 56 |
+
expect(() => allocate(0, [{ id: 'a', weight: 1 }])).toThrow(SplitError);
|
| 57 |
+
expect(fieldOf(() => allocate(0, [{ id: 'a', weight: 1 }]))).toBe('amount');
|
| 58 |
+
});
|
| 59 |
+
|
| 60 |
+
it('rejects a zero weight with field "shares"', () => {
|
| 61 |
+
expect(() => allocate(100, [{ id: 'a', weight: 0 }, { id: 'b', weight: 1 }])).toThrow(SplitError);
|
| 62 |
+
expect(fieldOf(() => allocate(100, [{ id: 'a', weight: 0 }, { id: 'b', weight: 1 }]))).toBe('shares');
|
| 63 |
+
});
|
| 64 |
+
|
| 65 |
+
it('rejects amounts that overflow safe-integer arithmetic', () => {
|
| 66 |
+
expect(() =>
|
| 67 |
+
allocate(6782420994015412, [
|
| 68 |
+
{ id: 'u0', weight: 1589 },
|
| 69 |
+
{ id: 'u1', weight: 7035 }
|
| 70 |
+
])
|
| 71 |
+
).toThrow(SplitError);
|
| 72 |
+
});
|
| 73 |
+
|
| 74 |
+
it('always sums to the total and is order-independent (property)', () => {
|
| 75 |
+
const rnd = mulberry32(42);
|
| 76 |
for (let i = 0; i < 500; i++) {
|
| 77 |
const n = 1 + Math.floor(rnd() * 8);
|
| 78 |
const total = 1 + Math.floor(rnd() * 1_000_000);
|
|
|
|
| 81 |
expect(sum(r)).toBe(total);
|
| 82 |
expect(Object.keys(r)).toHaveLength(n);
|
| 83 |
expect(Object.values(r).every((v) => v >= 0)).toBe(true);
|
| 84 |
+
|
| 85 |
+
const shuffled = [...weights].sort(() => rnd() - 0.5);
|
| 86 |
+
expect(allocate(total, shuffled)).toEqual(r);
|
| 87 |
}
|
| 88 |
});
|
| 89 |
});
|
|
|
|
| 103 |
expect(() => resolveShares(1000, { mode: 'exact', cents: { a: 1, b: 998 } })).toThrow(SplitError);
|
| 104 |
});
|
| 105 |
|
| 106 |
+
it('exact mode returns a copy of cents', () => {
|
| 107 |
+
const cents = { a: 400, b: 600 };
|
| 108 |
+
const result = resolveShares(1000, { mode: 'exact', cents });
|
| 109 |
+
result.a = 999;
|
| 110 |
+
expect(cents.a).toBe(400);
|
| 111 |
+
});
|
| 112 |
+
|
| 113 |
it('rejects empty or duplicate participants', () => {
|
| 114 |
expect(() => resolveShares(1000, { mode: 'equal', participants: [] })).toThrow(SplitError);
|
| 115 |
expect(() => resolveShares(1000, { mode: 'equal', participants: ['a', 'a'] })).toThrow(SplitError);
|