diff --git a/CHANGES.md b/CHANGES.md index 9c38282..085764a 100644 --- a/CHANGES.md +++ b/CHANGES.md @@ -1,6 +1,7 @@ # Changes ## Unreleased +- discount(items, percent) takes a percentage off the subtotal before tax and returns the rounded total. ## 1.2.0 - total() rounds through roundCents(). diff --git a/src/lib/cart.js b/src/lib/cart.js index 385fd69..cd515c5 100644 --- a/src/lib/cart.js +++ b/src/lib/cart.js @@ -8,3 +8,10 @@ export function subtotal(items) { export function total(items) { return roundCents(subtotal(items) * (1 + TAX_RATE)); } + +/** Returns the total after taking `percent` off the subtotal, before tax. */ +export function discount(items, percent) { + const validItems = items.filter((item) => item.qty > 0); + const discounted = subtotal(validItems) * (1 - percent / 100); + return roundCents(discounted * (1 + TAX_RATE)); +} diff --git a/tests/lib/cart.test.js b/tests/lib/cart.test.js index 7a9eab3..1074901 100644 --- a/tests/lib/cart.test.js +++ b/tests/lib/cart.test.js @@ -1,6 +1,8 @@ import { test } from 'node:test'; import assert from 'node:assert/strict'; -import { subtotal, total } from '../../src/lib/cart.js'; +import { subtotal, total, discount } from '../../src/lib/cart.js'; +import { TAX_RATE } from '../../src/generated/rates.js'; +import { roundCents } from '../../src/lib/money.js'; const items = [{ price: 10, qty: 2 }, { price: 5, qty: 1 }]; @@ -11,3 +13,34 @@ test('subtotal adds price times quantity', () => { test('total applies tax and rounds to cents', () => { assert.equal(total(items), 27); }); + +test('discount takes the percentage off before tax', () => { + assert.equal(discount(items, 10), roundCents(22.5 * (1 + TAX_RATE))); +}); + +test('discount of zero percent equals the total', () => { + assert.equal(discount(items, 0), total(items)); +}); + +test('discount of an empty cart is zero', () => { + assert.equal(discount([], 10), 0); +}); + +test('discount ignores items with zero or negative quantity', () => { + const cart = [...items, { price: 100, qty: 0 }, { price: 100, qty: -1 }]; + assert.equal(discount(cart, 10), discount(items, 10)); +}); + +test('discount of 100 percent is zero', () => { + assert.equal(discount(items, 100), 0); +}); + +test('discount rounds once at the end on a half-cent boundary', () => { + const cart = [{ price: 1.005, qty: 1 }]; + assert.equal(discount(cart, 0), roundCents(1.005 * (1 + TAX_RATE))); +}); + +test('discount handles large numbers', () => { + const cart = [{ price: 1000000, qty: 1000 }]; + assert.equal(discount(cart, 10), roundCents(900000000 * (1 + TAX_RATE))); +});