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..379e10c 100644 --- a/src/lib/cart.js +++ b/src/lib/cart.js @@ -8,3 +8,16 @@ export function subtotal(items) { export function total(items) { return roundCents(subtotal(items) * (1 + TAX_RATE)); } + +// `people` is a head count or an array of people. Shares sum exactly to total(); +// leftover cents go one each to the first people. +export function splitBill(items, people) { + const count = Array.isArray(people) ? people.length : people; + if (!Number.isInteger(count) || count < 1) { + throw new RangeError('splitBill needs at least one person'); + } + const cents = Math.trunc(total(items) * 100 + 0.5); + const base = Math.trunc(cents / count); + const extra = cents - base * count; + return Array.from({ length: count }, (_, i) => roundCents((base + (i < extra ? 1 : 0)) / 100)); +} diff --git a/tests/lib/cart.test.js b/tests/lib/cart.test.js index 7a9eab3..f04a25f 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,34 @@ test('subtotal adds price times quantity', () => { test('total applies tax and rounds to cents', () => { assert.equal(total(items), 27); }); + +const sum = (xs) => xs.reduce((a, b) => a + b, 0); + +test('splitBill splits the taxed total evenly', () => { + assert.deepEqual(splitBill(items, 3), [9, 9, 9]); + assert.deepEqual(splitBill(items, 1), [27]); +}); + +test('splitBill shares add up to the total, spreading leftover cents', () => { + const odd = [{ price: 10, qty: 1 }]; + const shares = splitBill(odd, 7); + assert.equal(shares.length, 7); + assert.equal(roundCents(sum(shares)), total(odd)); + assert.ok(Math.max(...shares) - Math.min(...shares) < 0.011); + assert.deepEqual(splitBill([{ price: 0.01, qty: 1 }], 3), [0.01, 0, 0]); +}); + +test('splitBill accepts a head count or a list of people', () => { + assert.deepEqual(splitBill(items, ['a', 'b', 'c']), [9, 9, 9]); +}); + +test('splitBill of an empty cart is all zeros', () => { + assert.deepEqual(splitBill([], 2), [0, 0]); +}); + +test('splitBill rejects invalid people', () => { + assert.throws(() => splitBill(items, 0), RangeError); + assert.throws(() => splitBill(items, []), RangeError); + assert.throws(() => splitBill(items, -2), RangeError); + assert.throws(() => splitBill(items, 1.5), RangeError); +});