diff --git a/README.md b/README.md new file mode 100644 index 0000000..7c2f62c --- /dev/null +++ b/README.md @@ -0,0 +1,20 @@ +# cart-app + +## Cart functions (`src/lib/cart.js`) + +- `subtotal(items)` — sum of `price * qty` across all items, before tax. +- `discount(items, percent)` — total including tax after taking `percent` off the subtotal before tax, rounded to cents. +- `itemCount(items)` — total quantity across all items. +- `total(items)` — subtotal plus tax, rounded to cents. + +## Running the checks + +``` +npm run check +``` + +This runs `scripts/check.mjs` and then the test suite. To run only the tests: + +``` +npm test +``` diff --git a/src/lib/cart.js b/src/lib/cart.js index 385fd69..b325db5 100644 --- a/src/lib/cart.js +++ b/src/lib/cart.js @@ -5,6 +5,15 @@ export function subtotal(items) { return items.reduce((sum, item) => sum + item.price * item.qty, 0); } +export function discount(items, percent) { + const discounted = subtotal(items) * (1 - percent / 100); + return roundCents(discounted * (1 + TAX_RATE)); +} + +export function itemCount(items) { + return items.reduce((sum, item) => sum + item.qty, 0); +} + export function total(items) { return roundCents(subtotal(items) * (1 + TAX_RATE)); } diff --git a/tests/lib/cart.test.js b/tests/lib/cart.test.js index 7a9eab3..6cdcffd 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, itemCount } 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,13 @@ test('subtotal adds price times quantity', () => { test('total applies tax and rounds to cents', () => { assert.equal(total(items), 27); }); + +test('itemCount sums quantities across items', () => { + assert.equal(itemCount(items), 3); + assert.equal(itemCount([]), 0); +}); + +test('discount takes percent off the subtotal before tax', () => { + assert.equal(discount(items, 10), roundCents(22.5 * (1 + TAX_RATE))); + assert.equal(discount(items, 0), total(items)); +});