diff --git a/CHANGES.md b/CHANGES.md index 9c38282..5525442 100644 --- a/CHANGES.md +++ b/CHANGES.md @@ -1,6 +1,7 @@ # Changes ## Unreleased +- Add splitBill(items, people) to the cart module: splits total() (incl. tax) into cent-exact shares. ## 1.2.0 - total() rounds through roundCents(). diff --git a/src/lib/cart.js b/src/lib/cart.js index 385fd69..36be014 100644 --- a/src/lib/cart.js +++ b/src/lib/cart.js @@ -8,3 +8,19 @@ export function subtotal(items) { export function total(items) { return roundCents(subtotal(items) * (1 + TAX_RATE)); } + +// Splits total(items) between `people` (a count, or an array of people). +// Shares are in cents-exact amounts that sum to the total; leftover cents +// go one each to the first people. +export function splitBill(items, people) { + const n = Array.isArray(people) ? people.length : people; + if (!Number.isInteger(n) || n < 1) { + throw new RangeError('splitBill: people must be a positive integer or non-empty array'); + } + const t = total(items); + const base = roundCents(t / n); + const diffCents = roundCents(roundCents(t - base * n) * 100); // whole cents, may be negative + const step = diffCents < 0 ? -0.01 : 0.01; + const extra = Math.abs(diffCents); + return Array.from({ length: n }, (_, i) => (i < extra ? roundCents(base + step) : base)); +} diff --git a/tests/lib/cart.test.js b/tests/lib/cart.test.js index 7a9eab3..0b2fa33 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,24 @@ test('subtotal adds price times quantity', () => { test('total applies tax and rounds to cents', () => { assert.equal(total(items), 27); }); + +test('splitBill splits the taxed total evenly', () => { + assert.deepEqual(splitBill(items, 3), [9, 9, 9]); +}); + +test('splitBill shares sum exactly to the total; extra cents go to the first people', () => { + const one = [{ price: 10, qty: 1 }]; // total 10.80 + const shares = splitBill(one, 7); + assert.deepEqual(shares, [1.55, 1.55, 1.54, 1.54, 1.54, 1.54, 1.54]); + assert.equal(Math.round(shares.reduce((a, b) => a + b, 0) * 100), 1080); + assert.deepEqual(splitBill([{ price: 0.01, qty: 1 }], 3), [0.01, 0, 0]); +}); + +test('splitBill accepts an array of people', () => { + assert.deepEqual(splitBill(items, ['a', 'b']), [13.5, 13.5]); +}); + +test('splitBill rejects invalid people counts', () => { + assert.throws(() => splitBill(items, 0)); + assert.throws(() => splitBill(items, 1.5)); +});