diff --git a/CHANGES.md b/CHANGES.md index 9c38282..514a822 100644 --- a/CHANGES.md +++ b/CHANGES.md @@ -1,6 +1,7 @@ # Changes ## Unreleased +- Added discount(items, percent), which returns the total after a percentage discount applied before tax. ## 1.2.0 - total() rounds through roundCents(). diff --git a/src/lib/cart.js b/src/lib/cart.js index 385fd69..4001afa 100644 --- a/src/lib/cart.js +++ b/src/lib/cart.js @@ -8,3 +8,9 @@ export function subtotal(items) { export function total(items) { return roundCents(subtotal(items) * (1 + TAX_RATE)); } + +/** Returns the cart total in dollars after taking percent off the subtotal, before tax. */ +export function discount(items, percent) { + const discounted = subtotal(items) * (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..bae87fa 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 { discount, subtotal, total } from '../../src/lib/cart.js'; const items = [{ price: 10, qty: 2 }, { price: 5, qty: 1 }]; @@ -11,3 +11,15 @@ 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 is applied', () => { + assert.equal(discount(items, 10), 24.3); +}); + +test('discount of zero percent equals the plain total', () => { + assert.equal(discount(items, 0), total(items)); +}); + +test('discount of an empty cart is zero', () => { + assert.equal(discount([], 10), 0); +});