diff --git a/CHANGES.md b/CHANGES.md index 9c38282..42eb7d1 100644 --- a/CHANGES.md +++ b/CHANGES.md @@ -1,6 +1,7 @@ # Changes ## Unreleased +- Add discount(items, percent): total after a percentage off, before tax. ## 1.2.0 - total() rounds through roundCents(). diff --git a/src/lib/cart.js b/src/lib/cart.js index 385fd69..332f9ce 100644 --- a/src/lib/cart.js +++ b/src/lib/cart.js @@ -8,3 +8,7 @@ export function subtotal(items) { export function total(items) { return roundCents(subtotal(items) * (1 + TAX_RATE)); } + +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..5ac1a86 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,8 @@ test('subtotal adds price times quantity', () => { test('total applies tax and rounds to cents', () => { assert.equal(total(items), 27); }); + +test('discount takes percent off before tax', () => { + assert.equal(discount(items, 10), 24.3); + assert.equal(discount(items, 0), total(items)); +});