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..478a15b 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 the taxed total between `people` payers. Shares are rounded to cents and +// the last share absorbs any rounding remainder, so shares always sum to total(). +export function splitBill(items, people) { + if (!Number.isInteger(people) || people < 1) { + throw new RangeError('people must be a positive integer'); + } + const grand = total(items); + const each = roundCents(grand / people); + const shares = Array(people - 1).fill(each); + const paid = roundCents(each * (people - 1)); + shares.push(roundCents(grand - paid)); + return shares; +} diff --git a/tests/lib/cart.test.js b/tests/lib/cart.test.js index 7a9eab3..3677697 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,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 gives the rounding remainder to the last person', () => { + assert.deepEqual(splitBill([{ price: 10, qty: 1 }], 3), [3.6, 3.6, 3.6]); + // total 11.34 split 4 ways + assert.deepEqual(splitBill([{ price: 10, qty: 1 }, { price: 0.5, qty: 1 }], 4), [2.84, 2.84, 2.84, 2.82]); +}); + +test('splitBill shares sum to the total', () => { + const shares = splitBill(items, 7); + assert.equal(Math.round(shares.reduce((a, b) => a + b) * 100), 2700); +}); + +test('splitBill rejects invalid people counts', () => { + assert.throws(() => splitBill(items, 0), RangeError); + assert.throws(() => splitBill(items, 1.5), RangeError); +});