How a shop is built
How to split a program into data and small functions that pass results to each other.
Any program is data and transformations of data. In the shop:
- an item is an object
{ name, price, qty }; - the cart is an array of items;
- promo codes are an object "code → discount";
- an order is the result of a chain of functions: cart → total → discount → delivery → amount due.
const cart = [
{ name: "Cat food", price: 400, qty: 2 },
{ name: "Toy mouse", price: 150, qty: 1 },
];
const total = cart.reduce((sum, item) => sum + item.price * item.qty, 0);
console.log(total);reduce.Each step is a separate small function that takes data and returns a result. Functions don't change what they're given; they return something new. That makes them easy to check one at a time and to chain together.
function cartTotal(cart) {
return cart.reduce((sum, item) => sum + item.price * item.qty, 0);
}
function deliveryCost(total) {
return total >= 1000 ? 0 : 300;
}
const cart = [{ name: "Cat food", price: 400, qty: 2 }];
const total = cartTotal(cart);
console.log(total, deliveryCost(total));The next link is promo codes. That's not an if for every code but data: an object "code → discount percent". Marketing invents a new campaign — one line goes into the object, and the function stays the same.
const PROMOS = { FISH: 10, MEOW: 25 };
function applyPromo(total, code) {
const percent = PROMOS[code] ?? 0;
return total - Math.round((total * percent) / 100);
}
console.log(applyPromo(1000, "FISH"));
console.log(applyPromo(1000, "MEOW"));
console.log(applyPromo(1000, "WOOF"));Now the whole chain. Read orderTotal top to bottom, like a recipe: total the cart, apply the promo code, add delivery. Every line is a call to a function with a clear name, and none of them knows how the others work.
const PROMOS = { FISH: 10 };
const cartTotal = (cart) => cart.reduce((sum, item) => sum + item.price * item.qty, 0);
const applyPromo = (total, code) => total - Math.round((total * (PROMOS[code] ?? 0)) / 100);
const deliveryCost = (total) => (total >= 1000 ? 0 : 300);
function orderTotal(cart, code) {
const subtotal = applyPromo(cartTotal(cart), code);
return subtotal + deliveryCost(subtotal);
}
const big = [
{ name: "Cat food", price: 400, qty: 2 },
{ name: "Cat bed", price: 900, qty: 1 },
];
console.log(orderTotal(big, "FISH"));
console.log(orderTotal([{ name: "Toy mouse", price: 150, qty: 1 }], ""));function addToCartBad(cart, item) {
cart.push(item);
return cart;
}
const saved = [{ name: "Cat food", price: 400, qty: 1 }];
const next = addToCartBad(saved, { name: "Toy mouse", price: 150, qty: 1 });
console.log(saved.length);
console.log(next === saved);saved is yesterday's order in the purchase history.The finishing touch is the server. Placing an order goes over the network, so it's asynchronous, and it can end in an error: an empty cart, no connection, an item sold out. So you'll need async, await and throw.
function sendOrder(cart) {
return new Promise((resolve, reject) => {
setTimeout(() => {
if (cart.length === 0) reject(new Error("the cart is empty"));
else resolve({ id: 42, status: "accepted" });
}, 300);
});
}
async function checkout(cart) {
try {
const order = await sendOrder(cart);
return "Order #" + order.id + " " + order.status;
} catch (error) {
return "That didn't work: " + error.message;
}
}
console.log(await checkout([{ name: "Cat food", price: 400, qty: 1 }]));
console.log(await checkout([]));sendOrder pretends to be a server: it thinks for 300 ms and either accepts the order or refuses.Notice where try…catch lives: not in every small function, but at the top, in checkout. Only there do we know what to tell the customer. Small functions honestly report a problem with throw or a rejected promise, and the decision is made by whoever put them together.
Pop quiz
Mistakes are fine: keep trying until you find the right answer, and Byte explains why it's right.