diff --git a/CHANGES.md b/CHANGES.md index 9c38282..687d622 100644 --- a/CHANGES.md +++ b/CHANGES.md @@ -1,6 +1,7 @@ # Changes ## Unreleased +- Add splitBill(items, people) to split the taxed total between people. ## 1.2.0 - total() rounds through roundCents(). diff --git a/src/lib/cart.js b/src/lib/cart.js index 385fd69..121e4c2 100644 --- a/src/lib/cart.js +++ b/src/lib/cart.js @@ -8,3 +8,18 @@ export function subtotal(items) { export function total(items) { return roundCents(subtotal(items) * (1 + TAX_RATE)); } + +// Splits total(items) between `people`; shares differ by at most a cent and sum to the total. +export function splitBill(items, people) { + if (!Number.isInteger(people) || people < 1) { + throw new RangeError('people must be a positive integer'); + } + const shares = []; + let remaining = total(items); + for (let i = 0; i < people; i++) { + const share = roundCents(remaining / (people - i)); + 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..948a455 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,20 @@ 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, 2), [13.5, 13.5]); +}); + +test('splitBill shares always add up to the total', () => { + 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.01 + 1e-9); +}); + +test('splitBill rejects invalid people counts', () => { + assert.throws(() => splitBill(items, 0), RangeError); + assert.throws(() => splitBill(items, 1.5), RangeError); +});