Skip to content
KALANBLON
Show contents

Chapter 6 of 7 · 25 min

Project: an online shop's cart

By the end of this chapter, you'll be able to

  • Model a business domain with interfaces and discriminated unions
  • Write a reusable generic class
  • Validate outside data before using it
  • Compute an exact total by working in whole units

The model

Prices are in CFA francs, a currency without cents: we store them as whole numbers, which avoids the rounding errors of decimal numbers. A discount can be a percentage, a fixed amount, or “3 for the price of 2”.

interface Product {
  readonly id: number;
  name: string;
  price: number;
}

type Discount =
  | { kind: "percentage"; rate: number }
  | { kind: "amount"; value: number }
  | { kind: "bundle"; bought: number; free: number };

interface Line {
  product: Product;
  quantity: number;
  discount?: Discount;
}

function linePrice(l: Line): number {
  const gross = l.product.price * l.quantity;
  const d = l.discount;
  if (!d) return gross;
  switch (d.kind) {
    case "percentage":
      return Math.round(gross * (1 - d.rate));
    case "amount":
      return Math.max(0, gross - d.value);
    case "bundle": {
      const bundles = Math.floor(l.quantity / (d.bought + d.free));
      return gross - bundles * d.free * l.product.price;
    }
    default: {
      const missed: never = d;
      return missed;
    }
  }
}

const fabric: Product = { id: 1, name: "Bogolan fabric", price: 7500 };
console.log(linePrice({ product: fabric, quantity: 2 }));
console.log(linePrice({ product: fabric, quantity: 2, discount: { kind: "percentage", rate: 0.1 } }));
console.log(linePrice({ product: fabric, quantity: 3, discount: { kind: "bundle", bought: 2, free: 1 } }));
15000
13500
15000

For the “buy 2, get 1 free” bundle, every group of 3 items includes 1 free: with 3 fabrics, you pay for 2.

A generic repository

The catalogue and, later, customers or orders need the same operations: add, find by identifier, list. A generic class writes them only once, for any type that has an id:

class Repository<T extends { readonly id: number }> {
  private items = new Map<number, T>();

  add(e: T): void {
    if (this.items.has(e.id)) throw new Error(`identifier ${e.id} already used`);
    this.items.set(e.id, e);
  }

  find(id: number): T | undefined {
    return this.items.get(id);
  }

  all(): T[] {
    return [...this.items.values()];
  }
}

const catalogue = new Repository<{ readonly id: number; name: string }>();
catalogue.add({ id: 1, name: "Woven basket" });
catalogue.add({ id: 2, name: "Bead bracelet" });
console.log(catalogue.find(2)?.name, catalogue.all().length);
try {
  catalogue.add({ id: 1, name: "Duplicate" });
} catch (e) {
  console.log(e instanceof Error ? e.message : e);
}
Bead bracelet 2
identifier 1 already used

private stops the rest of the program from touching the Map directly: it has to go through the methods, which check for duplicates.

The total adds up the lines, as whole numbers: no rounding error.

Step 5 of 5
Text description of the animation
  1. The catalogue arrives as text, from an API.
  2. Each entry is checked. Invalid entries are discarded and reported.
  3. Valid products are stored in the generic repository.
  4. The customer fills the cart. Each discount is a variant of the union.
  5. The total adds up the lines, as whole numbers: no rounding error.

Load and validate the catalogue

The catalogue comes from an API. We receive it as unknown, keep what is valid and report the rest:

interface Product {
  readonly id: number;
  name: string;
  price: number;
}

function isProduct(v: unknown): v is Product {
  return typeof v === "object" && v !== null &&
    "id" in v && Number.isInteger(v.id) &&
    "name" in v && typeof v.name === "string" && v.name.length > 0 &&
    "price" in v && Number.isInteger(v.price) && (v.price as number) > 0;
}

function api(): Promise<string> {
  return new Promise((ok) => setTimeout(() => ok(
    '[{"id": 1, "name": "Woven basket", "price": 12000}, {"id": 2, "name": "", "price": 500}, {"id": 3, "name": "Necklace", "price": 4500.5}, {"id": 4, "name": "Wooden mask", "price": 25000}]'
  ), 30));
}

async function loadCatalogue(): Promise<Product[]> {
  const data: unknown = JSON.parse(await api());
  if (!Array.isArray(data)) throw new Error("unreadable catalogue");
  const valid = data.filter(isProduct);
  console.log(`${valid.length} products loaded, ${data.length - valid.length} rejected`);
  return valid;
}

const products = await loadCatalogue();
console.log(products.map((p) => p.name));
2 products loaded, 2 rejected
["Woven basket","Wooden mask"]

The product without a name and the one whose price is not a whole number are rejected. Number.isInteger accepts any value and returns false if it is not an integer: it works as a test, but does not narrow the type, hence the (v.price as number) right after, a safe assertion since the test has just taken place.

Mini-lab: your cartTypeScript

Output

Click “Run”: the TypeScript compiler will be loaded in your browser (about 3 MB the first time). Your code is checked, then run if it has no type error.

Your code runs in your browser, isolated from the page. · Ctrl/⌘ + Enter to run · Esc then Tab to leave the editor

Your turn

Worked exercise

Worked exercise: free delivery

Add to the project a function cartTotal(lines) that adds up the lines, then adds a 2,000 FCFA delivery fee, free from 30,000 FCFA of purchases. It returns an object { subtotal, delivery, total }. Test it with a cart of 2 fabrics at 7,500 FCFA (10% discount) and with a cart of 3 fabrics in a “2 + 1 free” bundle plus a mask at 25,000 FCFA.

Hint 1
Reuse linePrice and reduce for the subtotal.
Hint 2
Declare a Total interface for the result: the return type documents the function.
Show the solution and common mistakes
interface Product { readonly id: number; name: string; price: number }
type Discount =
  | { kind: "percentage"; rate: number }
  | { kind: "bundle"; bought: number; free: number };
interface Line { product: Product; quantity: number; discount?: Discount }
interface Total { subtotal: number; delivery: number; total: number }

const DELIVERY_FEE = 2000;
const FREE_DELIVERY_THRESHOLD = 30000;

function linePrice(l: Line): number {
  const gross = l.product.price * l.quantity;
  const d = l.discount;
  if (!d) return gross;
  switch (d.kind) {
    case "percentage":
      return Math.round(gross * (1 - d.rate));
    case "bundle":
      return gross - Math.floor(l.quantity / (d.bought + d.free)) * d.free * l.product.price;
  }
}

function cartTotal(lines: Line[]): Total {
  const subtotal = lines.reduce((t, l) => t + linePrice(l), 0);
  const delivery = subtotal >= FREE_DELIVERY_THRESHOLD ? 0 : DELIVERY_FEE;
  return { subtotal, delivery, total: subtotal + delivery };
}

const fabric: Product = { id: 1, name: "Bogolan fabric", price: 7500 };
const mask: Product = { id: 4, name: "Wooden mask", price: 25000 };
console.log(cartTotal([{ product: fabric, quantity: 2, discount: { kind: "percentage", rate: 0.1 } }]));
console.log(cartTotal([
  { product: fabric, quantity: 3, discount: { kind: "bundle", bought: 2, free: 1 } },
  { product: mask, quantity: 1 },
]));
{"subtotal":13500,"delivery":2000,"total":15500}
{"subtotal":40000,"delivery":0,"total":40000}

The thresholds are named constants: the day the shop changes its delivery policy, there is only one line to change.

Common mistakes:

  • Testing subtotal > 30000 instead of >=: a cart of exactly 30,000 FCFA would pay for delivery, contrary to the announced rule.
  • Computing delivery on the price before discounts: a customer with a discount would wrongly believe they qualify for free delivery.

Summary

  1. 1Discriminated unions model business variants, such as kinds of discounts.
  2. 2A constrained generic class (T extends { id: number }) is reused for any type with an identifier.
  3. 3API data is validated by a type guard before entering the catalogue.
  4. 4Money is computed in whole units: never decimals for amounts.
  5. 5Business rules (thresholds, fees) live in named constants.

Your progress is saved on this device. Create a free account to keep your progress on all your devices.