diff --git a/CHANGES.md b/CHANGES.md index 9c38282..61b9193 100644 --- a/CHANGES.md +++ b/CHANGES.md @@ -1,6 +1,8 @@ # Changes ## Unreleased +- discount(items, percent) returns the total after taking a percentage off before tax. +- subtotal() now ignores items with a quantity of 0 or less. ## 1.2.0 - total() rounds through roundCents(). diff --git a/src/lib/cart.js b/src/lib/cart.js index 385fd69..3fe3c99 100644 --- a/src/lib/cart.js +++ b/src/lib/cart.js @@ -1,10 +1,19 @@ import { TAX_RATE } from '../generated/rates.js'; import { roundCents } from './money.js'; +/** Returns the pre-tax sum of price times qty, ignoring items with qty of 0 or less. */ export function subtotal(items) { - return items.reduce((sum, item) => sum + item.price * item.qty, 0); + return items + .filter((item) => item.qty > 0) + .reduce((sum, item) => sum + item.price * item.qty, 0); } +/** Returns the cart total with tax, rounded to cents. */ export function total(items) { return roundCents(subtotal(items) * (1 + TAX_RATE)); } + +/** Returns the total after taking percent off the subtotal, then applying tax, rounded to cents. */ +export function discount(items, percent) { + return roundCents(subtotal(items) * (1 - percent / 100) * (1 + TAX_RATE)); +} diff --git a/tests/lib/cart.test.js b/tests/lib/cart.test.js index 7a9eab3..c020c38 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, discount } from '../../src/lib/cart.js'; const items = [{ price: 10, qty: 2 }, { price: 5, qty: 1 }]; @@ -11,3 +11,32 @@ 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), 24.3); +}); + +test('discount of zero percent equals 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 extra = [...items, { price: 100, qty: 0 }, { price: 100, qty: -1 }]; + assert.equal(discount(extra, 10), 24.3); +}); + +test('discount rounds once at the end on a half-cent boundary', () => { + assert.equal(discount([{ price: 1.005, qty: 1 }], 50), 0.54); +}); + +test('discount of 100 percent is free', () => { + assert.equal(discount(items, 100), 0); +}); + +test('discount handles large amounts', () => { + assert.equal(discount([{ price: 1000000, qty: 1000 }], 10), 972000000); +});