Let's build the brain of a cinema ticket machine. Ticket prices depend on the customer's age, whether it's a matinee (daytime) show, and whether they have a student card.
// ---- Customer details (try changing these!) ----
const age = 20;
const isStudent = true;
const showTime = 14; // 24-hour clock: 14 means 2 pm
// ---- Work out the base price ----
let price;
let category;
if (age < 3) {
price = 0;
category = "Baby (free!)";
} else if (age < 13) {
price = 30;
category = "Child";
} else if (age >= 65) {
price = 35;
category = "Senior";
} else {
price = 60;
category = "Adult";
}
// ---- Discounts ----
const isMatinee = showTime < 17;
if (isMatinee && price > 0) {
price -= 10;
}
if (isStudent && category === "Adult") {
price = price * 0.8; // 20% off
}
// ---- Print the ticket ----
console.log("🎬 ======= TICKET ======= 🎬");
console.log(`Category: ${category}`);
console.log(`Show time: ${showTime}:00 ${isMatinee ? "(matinee discount)" : ""}`);
console.log(`Student discount: ${isStudent && category === "Adult" ? "yes" : "no"}`);
console.log(`Price: $${price.toFixed(2)}`);
console.log(price === 0 ? "Enjoy the show, little one!" : "Enjoy the show!");
It prints
🎬 ======= TICKET ======= 🎬 Category: Adult Show time: 14:00 (matinee discount) Student discount: yes Price: $40.00 Enjoy the show!
Our adult started at $60, got $10 off for the matinee ($50), and then 20% off for being a student ($40). Nice deal!
Test the machine with different customers: a 2-year-old, an 8-year-old at an evening show (say, showTime = 19), a 70-year-old student, and a 30-year-old non-student at 9 pm. Does the machine always do the right thing? Can you find any cases where the rules seem unfair?