diff --git a/CHANGES.md b/CHANGES.md index 9c38282..8d97166 100644 --- a/CHANGES.md +++ b/CHANGES.md @@ -1,6 +1,7 @@ # Changes ## Unreleased +- Add splitBill(items, people): splits the taxed total; shares 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..9f9d6f0 100644 --- a/src/lib/cart.js +++ b/src/lib/cart.js @@ -1,5 +1,5 @@ import { TAX_RATE } from '../generated/rates.js'; -import { roundCents } from './money.js'; +import { roundCents, splitAmount } from './money.js'; export function subtotal(items) { return items.reduce((sum, item) => sum + item.price * item.qty, 0); @@ -8,3 +8,10 @@ export function subtotal(items) { export function total(items) { return roundCents(subtotal(items) * (1 + TAX_RATE)); } + +export function splitBill(items, people) { + if (!Number.isInteger(people) || people < 1) { + throw new RangeError('people must be a positive integer'); + } + return splitAmount(total(items), people); +} diff --git a/src/lib/money.js b/src/lib/money.js index 9f36d50..21f1093 100644 --- a/src/lib/money.js +++ b/src/lib/money.js @@ -2,3 +2,12 @@ export function roundCents(amount) { return Math.round((amount + Number.EPSILON) * 100) / 100; } + +// Splits an amount into `parts` shares that sum exactly to the amount in cents. +// Any leftover cents go one each to the first shares. +export function splitAmount(amount, parts) { + const cents = Math.round(roundCents(amount) * 100); + const base = Math.floor(cents / parts); + const extra = cents - base * parts; + return Array.from({ length: parts }, (_, i) => (base + (i < extra ? 1 : 0)) / 100); +} diff --git a/tests/lib/cart.test.js b/tests/lib/cart.test.js index 7a9eab3..53fa89a 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,18 @@ 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 leftover cents to the first people', () => { + // total 10.80 split 7 ways = 1.54 * 7 + 2 cents + const shares = splitBill([{ price: 10, qty: 1 }], 7); + assert.deepEqual(shares, [1.55, 1.55, 1.54, 1.54, 1.54, 1.54, 1.54]); +}); + +test('splitBill rejects invalid people counts', () => { + assert.throws(() => splitBill(items, 0), RangeError); + assert.throws(() => splitBill(items, 1.5), RangeError); +});