Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 8 additions & 9 deletions src/money/cents.ts
Original file line number Diff line number Diff line change
Expand Up @@ -29,22 +29,21 @@ export function parseCents(input: string): number {
/**
* Split an integer amount of cents evenly across member ids.
*
* SEEDED DEFECT (issue #2): this floors every share and drops the
* remainder instead of handing the leftover cents to the first N members,
* so the shares can sum to less than totalCents. `bun test` does not catch
* this because the baseline tests only split amounts that divide evenly.
* The correct remainder rule is documented in
* Applies the remainder rule: every member gets floor(totalCents / n), and
* the first `remainder` members (in the order passed) get one extra cent, so
* the shares always sum to exactly totalCents. See
* .claude/skills/handling-money/references/rules.md.
*/
export function splitCents(totalCents: number, memberIds: string[]): Record<string, number> {
if (memberIds.length === 0) {
throw new Error("cannot split among zero members");
}
const share = Math.floor(totalCents / memberIds.length);
const base = Math.floor(totalCents / memberIds.length);
const remainder = totalCents - base * memberIds.length;
const shares: Record<string, number> = {};
for (const id of memberIds) {
shares[id] = share;
}
memberIds.forEach((id, i) => {
shares[id] = i < remainder ? base + 1 : base;
});
return shares;
}

Expand Down
32 changes: 32 additions & 0 deletions tests/money.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -36,4 +36,36 @@ describe("splitCents", () => {
const shares = splitCents(2000, ["a", "b"]);
expect(sumCents(Object.values(shares))).toBe(2000);
});

test("gives leftover cents to the first members", () => {
const shares = splitCents(1000, ["a", "b", "c"]);
expect(shares).toEqual({ a: 334, b: 333, c: 333 });
expect(sumCents(Object.values(shares))).toBe(1000);
});

test("shares always sum to the total for uneven splits", () => {
const cases: Array<[number, number]> = [
[1001, 3],
[1, 3],
[2, 3],
[1000, 7],
[999, 4],
[5, 1],
];
for (const [total, n] of cases) {
const ids = Array.from({ length: n }, (_, i) => `m${i}`);
const shares = splitCents(total, ids);
const values = ids.map((id) => shares[id]!);
expect(sumCents(values)).toBe(total);
expect(Math.max(...values) - Math.min(...values)).toBeLessThanOrEqual(1);
// Extra cents go to the leading members, in input order.
const extra = total % n;
const base = Math.floor(total / n);
values.forEach((v, i) => expect(v).toBe(i < extra ? base + 1 : base));
}
});

test("throws when splitting among zero members", () => {
expect(() => splitCents(1000, [])).toThrow("cannot split among zero members");
});
});
Loading