diff --git a/CHANGES.md b/CHANGES.md index 9c38282..c661ccd 100644 --- a/CHANGES.md +++ b/CHANGES.md @@ -1,6 +1,7 @@ # Changes ## Unreleased +- Add splitBill(items, people): per-person shares of the taxed total that sum exactly to total(). ## 1.2.0 - total() rounds through roundCents(). diff --git a/src/lib/cart.js b/src/lib/cart.js index 385fd69..3f7baca 100644 --- a/src/lib/cart.js +++ b/src/lib/cart.js @@ -8,3 +8,15 @@ export function subtotal(items) { export function total(items) { return roundCents(subtotal(items) * (1 + TAX_RATE)); } + +// Splits total(items) (tax included) across `people`. Works in whole cents so the +// shares always add up exactly to the total; leftover cents go to the first people. +export function splitBill(items, people) { + if (!Number.isInteger(people) || people < 1) { + throw new RangeError('people must be a positive integer'); + } + const cents = roundCents(total(items) * 100); + const extra = cents % people; + const base = (cents - extra) / people; + return Array.from({ length: people }, (_, i) => roundCents((base + (i < extra ? 1 : 0)) / 100)); +} diff --git a/tests/lib/cart.test.js b/tests/lib/cart.test.js index 7a9eab3..80f5c96 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,19 @@ 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 gives leftover cents to the first people', () => { + // total is 0.54 -> 54 cents over 4 people + assert.deepEqual(splitBill([{ price: 0.5, qty: 1 }], 4), [0.14, 0.14, 0.13, 0.13]); + // total is 1.08 -> 36 cents each + assert.deepEqual(splitBill([{ price: 1, qty: 1 }], 3), [0.36, 0.36, 0.36]); +}); + +test('splitBill rejects invalid people counts', () => { + assert.throws(() => splitBill(items, 0), RangeError); + assert.throws(() => splitBill(items, 1.5), RangeError); +});