A small project: an inventory in three modules

The eleven lessons before this one each showed a feature on its own. This one puts them in a folder: four modules, three classes, one function that turns them into text, a program that runs the whole thing, and a test file that checks the parts. Nothing in it is new except the way the pieces fit.

The project is small on purpose. It is an inventory of items with a price and a quantity, and every line of it is either a class from the last lessons or a module from the two before. The last section runs the tests, which is what the next part of the course does with a real test runner.

The files and the item

Five files sit at the top of the folder and the test lives one level down, because the test is not part of the program. The project uses ES modules rather than CommonJS, because the files form one import graph and ES modules are the system the language defines, so the manifest below makes every .js in the folder a module and the imports work with no further setting.

package.json
item.js
inventory.js
report.js
main.js
tests/inventory.test.js

The file package.json:

{ "name": "inventory", "version": "1.0.0", "type": "module" }

The file item.js:

export class Item { #quantity; constructor(name, category, price, quantity) { this.name = name; this.category = category; this.price = price; this.#quantity = quantity; } get quantity() { return this.#quantity; } get value() { return this.price * this.#quantity; } add(count) { this.#quantity += count; return this; } remove(count) { if (count > this.#quantity) { throw new RangeError(`only ${this.#quantity} of ${this.name} left`); } this.#quantity -= count; return this; } }

An item has four fields and one of them is private. The constructor takes the values and writes the quantity through the private field, so the only ways to change it are the two methods below it. The price is kept in cents, which is the decision that keeps every sum exact: a floating point price would make a total drift by a cent.

The inventory holds the items

The inventory keeps items in a Map keyed by name, which gives it a lookup by name, one entry per name and an insertion order. The private field is a Map rather than a plain object, so a name such as constructor is an ordinary key. The getters answer with sorted names and with the total in cents, and the last method groups the names by category.

The file inventory.js:

export class Inventory { #items = new Map(); add(item) { this.#items.set(item.name, item); return this; } get(name) { return this.#items.get(name); } remove(name) { this.#items.delete(name); } get names() { return [...this.#items.keys()].sort(); } get totalCents() { let total = 0; for (const item of this.#items.values()) { total += item.value; } return total; } byCategory() { const groups = new Map(); for (const item of this.#items.values()) { const list = groups.get(item.category) ?? []; list.push(item.name); groups.set(item.category, list); } return groups; } }

The class owns the collection and offers the four questions a report needs: which names, how many, what total, and which category. The sorted names make the report stable, since a Map keeps insertion order and the report should not change when the program adds items in another order. Nothing here knows how money is printed, which is the next file.

The report turns data into text

A report module has no state and one job: turn an inventory into lines of text. Money is formatted here and nowhere else, so the rule of two decimals is written once, and the report itself is a list of strings joined at the end, which makes it easy to print or to check a line at a time. The module imports nothing, so it can be tested with a plain object that has the same methods.

The file report.js:

export function formatMoney(cents) { const sign = cents < 0 ? '-' : ''; const absolute = Math.abs(cents); const units = Math.floor(absolute / 100); const rest = String(absolute % 100).padStart(2, '0'); return `${sign}$${units}.${rest}`; } export function report(inventory) { const lines = [`items: ${inventory.names.length}`]; for (const name of inventory.names) { const item = inventory.get(name); const price = formatMoney(item.price); lines.push(`${name}: ${item.quantity} x ${price} = ${formatMoney(item.value)}`); } const categories = [...inventory.byCategory()] .map(([category, names]) => `${category}(${names.length})`); lines.push(`categories: ${categories.join(', ')}`); lines.push(`total: ${formatMoney(inventory.totalCents)}`); return lines.join('\n'); }

The formatting is integer arithmetic: cents are divided by a hundred once, and the remainder is padded to two digits. The report reads the inventory through its public methods only, which is what keeps the two files independent of each other. That independence is the reason the next file can put them together in ten lines.

The program that uses them

The program builds three items, adds them, removes four pencils and prints the report. It imports one class from each module and never touches a private field, which is the shape a small application has: one file that wires the parts and a set of files that know nothing about each other.

The file main.js:

import { Inventory } from './inventory.js'; import { Item } from './item.js'; import { report } from './report.js'; const inventory = new Inventory(); inventory.add(new Item('pencil', 'office', 50, 10)); inventory.add(new Item('notebook', 'office', 250, 3)); inventory.add(new Item('coffee', 'kitchen', 800, 2)); inventory.get('pencil').remove(4); console.log(report(inventory));

node main.js

items: 3
coffee: 2 x $8.00 = $16.00
notebook: 3 x $2.50 = $7.50
pencil: 6 x $0.50 = $3.00
categories: office(2), kitchen(1)
total: $26.50

Six pencils after the removal, the two office items counted apart from the kitchen one, and a total that adds up to the three lines above it. The names are sorted, so the report reads as a list rather than as the order of the calls that built it. The whole program is a dozen lines because the work sits in the classes.

Tests without a framework

A test file is a program that calls the code and compares the answers. The one below needs no package: node:assert/strict is part of Node.js, and a list of names and functions is enough to run the five checks and to report which one failed. The exit code is set at the end, so a script or a pipeline sees a failure as a failure.

The file tests/inventory.test.js:

import assert from 'node:assert/strict'; import { Inventory } from '../inventory.js'; import { Item } from '../item.js'; import { formatMoney, report } from '../report.js'; const tests = []; const test = (name, run) => tests.push([name, run]); test('the value is the price times the quantity', () => { assert.equal(new Item('pencil', 'office', 50, 10).value, 500); }); test('removing more than there is throws', () => { const pencil = new Item('pencil', 'office', 50, 2); assert.throws(() => pencil.remove(3), RangeError); }); test('the total adds every item', () => { const inventory = new Inventory(); inventory.add(new Item('pencil', 'office', 50, 10)); inventory.add(new Item('coffee', 'kitchen', 800, 2)); assert.equal(inventory.totalCents, 50 * 10 + 800 * 2); }); test('money has two decimals', () => { assert.equal(formatMoney(500), '$5.00'); assert.equal(formatMoney(5), '$0.05'); }); test('the report starts with the number of items', () => { const inventory = new Inventory(); inventory.add(new Item('pencil', 'office', 50, 1)); assert.equal(report(inventory).split('\n')[0], 'items: 1'); }); let failed = 0; for (const [name, run] of tests) { try { run(); console.log(`ok - ${name}`); } catch (error) { failed += 1; console.log(`not ok - ${name}: ${error.message}`); } } console.log(`${tests.length - failed} of ${tests.length} passed`); process.exitCode = failed === 0 ? 0 : 1;

node tests/inventory.test.js

ok - the value is the price times the quantity
ok - removing more than there is throws
ok - the total adds every item
ok - money has two decimals
ok - the report starts with the number of items
5 of 5 passed

Five lines of ok and a count, which is what a test run looks like in any runner. One of the five checks a thrown error, one checks a formatted string, and one checks a line of the report, so the three layers of the project each have a test. Change an expectation in the file and the matching line becomes not ok, with the message of the assertion after it.

Exercises

  1. Add a fourth item to main.js in a new category and print the report again. Which lines of the report change?
  2. Make Inventory.remove return the item it deleted, or undefined when the name was not there. Which test would you add for it?
  3. Write an item with a price of 5 cents and a quantity of 1 and check that formatMoney prints it with two decimals. Which line of the report would look wrong without the padding?
  4. Move formatMoney into its own module and import it in report.js. How many imports does report.js have then?
  5. Make a test that fails on purpose by changing the expected total. What does the run print, and what is the exit code?

Questions

A new set of questions in a new order every time. Choose one answer for each, then check.

  1. Why is the price of an item kept in cents?

    Answer

    Integer arithmetic keeps the totals exact

    A floating point price makes a sum drift, while integer cents add and multiply exactly.

  2. Which collection does the inventory use for its items, and why?

    Answer

    A Map, for a lookup by name and one entry per name

    The name is the key, the order is kept, and a name such as constructor is an ordinary key.

  3. Why does the report module import nothing?

    Answer

    It reads the inventory through its public methods only

    The report takes an object with the same methods, which keeps the two files independent.

  4. What does the test file use to compare values?

    Answer

    node:assert/strict, which ships with Node.js

    The assertion module is part of Node.js, so the test needs no dependency at all.

  5. A module contains: export class Box { #n = 1; get n() { return this.#n; } } console.log(Object.keys(new Box()).length); What does it print?

    Answer

    0

    The private field is not an own enumerable key, and the getter lives on the prototype.

  6. A module contains: export function money(cents) { return "$" + Math.floor(cents / 100) + "." + String(cents % 100).padStart(2, "0"); } console.log(money(5));

    Answer

    $0.05

    Five cents is zero units and five hundredths, and padStart writes the leading zero.

  7. A module contains: const names = ["pencil", "coffee", "notebook"]; console.log(names.sort().join(","));

    Answer

    coffee,notebook,pencil

    The default sort compares the strings, and c comes before n and n before p.

  8. A module contains: const m = new Map([["a", 1]]); m.set("a", 2); console.log(m.size);

    Answer

    1

    A map keeps one entry per key, so the second set replaced the value and did not add an entry.

  9. A test file contains: import assert from "node:assert/strict"; assert.equal(2 + 2, 5); console.log("after"); What does the run print?

    Answer

    Nothing, because the assertion throws an AssertionError

    A failed assertion throws an error, so the line after it never runs.

  10. A module contains: export class Counter { #n = 0; bump() { return ++this.#n; } } const c = new Counter(); c.bump(); console.log(c.bump());

    Answer

    2

    The private field keeps its value between calls, and the prefix increment returns the new one.

The code on this page was run with Node.js 24.22.1 and linted with ESLint 10.14.0 on Alpine Linux 3.24.3 (x86_64) in a Docker container.

Article author: Arthur Isaev

Banner image