diff --git a/CHANGES.md b/CHANGES.md index 9c38282..4a019b8 100644 --- a/CHANGES.md +++ b/CHANGES.md @@ -1,6 +1,7 @@ # Changes ## Unreleased +- Add splitBill(items, people) to the cart module. ## 1.2.0 - total() rounds through roundCents(). diff --git a/src/lib/cart.js b/src/lib/cart.js index 385fd69..d464b0c 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 the taxed total between `people`. Shares sum exactly to total(items); +// they differ by at most one cent. +export function splitBill(items, people) { + if (!Number.isInteger(people) || people < 1) { + throw new RangeError('people must be a positive integer'); + } + let remaining = total(items); + const shares = []; + for (let left = people; left > 0; left--) { + const share = roundCents(remaining / left); + shares.push(share); + remaining = roundCents(remaining - share); + } + return shares; +} diff --git a/tests/lib/cart.test.js b/tests/lib/cart.test.js index 7a9eab3..4004120 100644 --- a/tests/lib/cart.test.js +++ b/tests/lib/cart.test.js @@ -1,6 +1,7 @@ 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'; +import { roundCents } from '../../src/lib/money.js'; const items = [{ price: 10, qty: 2 }, { price: 5, qty: 1 }]; @@ -11,3 +12,23 @@ 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 to the total, differing by at most a cent', () => { + const odd = [{ price: 10, qty: 1 }]; + const shares = splitBill(odd, 3); + assert.equal(shares.length, 3); + assert.equal(roundCents(shares.reduce((a, b) => a + b, 0)), total(odd)); + assert.ok(Math.max(...shares) - Math.min(...shares) <= 0.011); +}); + +test('splitBill with one person returns the whole total', () => { + assert.deepEqual(splitBill(items, 1), [27]); +}); + +test('splitBill rejects invalid people counts', () => { + for (const n of [0, -1, 1.5, NaN]) assert.throws(() => splitBill(items, n), RangeError); +});