diff --git a/CHANGES.md b/CHANGES.md index 9c38282..23fa809 100644 --- a/CHANGES.md +++ b/CHANGES.md @@ -1,6 +1,7 @@ # Changes ## Unreleased +- Add splitBill(items, people): splits the taxed total into per-person shares that sum exactly to total(). ## 1.2.0 - total() rounds through roundCents(). diff --git a/src/lib/cart.js b/src/lib/cart.js index 385fd69..c4baf20 100644 --- a/src/lib/cart.js +++ b/src/lib/cart.js @@ -8,3 +8,17 @@ export function subtotal(items) { export function total(items) { return roundCents(subtotal(items) * (1 + TAX_RATE)); } + +// Splits total(items) between `people`. Shares are whole cents, differ by at +// most one cent, and always sum exactly to the total. +export function splitBill(items, people) { + if (!Number.isInteger(people) || people < 1) { + throw new RangeError('people must be a positive integer'); + } + const t = total(items); + // Each share is the difference of rounded cumulative amounts, so the + // rounding error never accumulates and the shares telescope to t. + return Array.from({ length: people }, (_, i) => + roundCents(roundCents((t * (i + 1)) / people) - roundCents((t * i) / people)), + ); +} diff --git a/tests/lib/cart.test.js b/tests/lib/cart.test.js index 7a9eab3..cafcfdf 100644 --- a/tests/lib/cart.test.js +++ b/tests/lib/cart.test.js @@ -1,6 +1,6 @@ import { test } from 'node:test'; import assert from 'node:assert/strict'; -import { subtotal, total } from '../../src/lib/cart.js'; +import { subtotal, total, splitBill } from '../../src/lib/cart.js'; const items = [{ price: 10, qty: 2 }, { price: 5, qty: 1 }]; @@ -11,3 +11,37 @@ test('subtotal adds price times quantity', () => { test('total applies tax and rounds to cents', () => { assert.equal(total(items), 27); }); + +const sum = (a) => a.reduce((x, y) => x + y, 0); +const toCents = (a) => a.map((s) => Math.round(s * 100)); + +test('splitBill splits the taxed total evenly', () => { + assert.deepEqual(splitBill(items, 3), [9, 9, 9]); +}); + +test('splitBill with one person returns the whole total', () => { + assert.deepEqual(splitBill(items, 1), [27]); +}); + +test('splitBill distributes leftover cents so shares sum to the total', () => { + const shares = splitBill([{ price: 10, qty: 1 }], 7); // total 10.80 + assert.equal(shares.length, 7); + assert.equal(sum(toCents(shares)), 1080); + const c = toCents(shares); + assert.ok(Math.max(...c) - Math.min(...c) <= 1); +}); + +test('splitBill handles a total smaller than one cent per person', () => { + const shares = splitBill([{ price: 0.01, qty: 1 }], 3); // total 0.01 + assert.deepEqual(toCents(shares).sort(), [0, 0, 1]); +}); + +test('splitBill on an empty cart gives everyone 0', () => { + assert.deepEqual(splitBill([], 3), [0, 0, 0]); +}); + +test('splitBill rejects invalid people counts', () => { + for (const n of [0, -1, 1.5, NaN, undefined, '2']) { + assert.throws(() => splitBill(items, n), RangeError); + } +});