diff --git a/README.md b/README.md new file mode 100644 index 0000000..c4dd9a4 --- /dev/null +++ b/README.md @@ -0,0 +1,14 @@ +# cart-app + +## `src/lib/cart.js` + +- `subtotal(items)` — sum of `price * qty` across items, before tax. +- `itemCount(items)` — total quantity of all items. +- `discount(items, percent)` — subtotal reduced by `percent`%, then taxed and rounded to cents. +- `total(items)` — subtotal plus tax (`TAX_RATE`), rounded to cents. + +## Running the checks + +- `npm test` — runs the unit tests (`node --test "tests/**/*.test.js"`). +- `npm run check` — runs `scripts/check.mjs`, then the tests. +- `npm run gen` — runs `scripts/gen.mjs` (generates files such as `src/generated/rates.js`). diff --git a/src/lib/cart.js b/src/lib/cart.js index 385fd69..696ac0d 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 itemCount(items) { + return items.reduce((sum, item) => sum + item.qty, 0); +} + +export function discount(items, percent) { + const discounted = subtotal(items) * (1 - percent / 100); + return roundCents(discounted * (1 + TAX_RATE)); +} + 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..93dbb3f 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, itemCount } from '../../src/lib/cart.js'; const items = [{ price: 10, qty: 2 }, { price: 5, qty: 1 }]; @@ -8,6 +8,16 @@ test('subtotal adds price times quantity', () => { assert.equal(subtotal(items), 25); }); +test('itemCount sums quantities across items', () => { + assert.equal(itemCount(items), 3); + assert.equal(itemCount([]), 0); +}); + test('total applies tax and rounds to cents', () => { assert.equal(total(items), 27); }); + +test('discount is taken off the subtotal before tax', () => { + assert.equal(discount(items, 20), 21.6); + assert.equal(discount(items, 0), total(items)); +});