Complete these exercises after the session. They build on callbacks, delayed execution, and reduce.
Copy import { teas } from " ../data/teas.js " ;
import fs from " fs " ; Exercise 1: Stock by Caffeine Level
Use reduce to calculate the total stock for each caffeine level:
Copy function stockByCaffeine ( teas ) {
return teas . reduce ( ( acc , tea ) => {
// Your implementation
}, {} ) ;
}
console . log ( stockByCaffeine ( teas )) ;
// { high: 745, medium: 450, low: 190, none: 635 } This tells you how much inventory you have for customers who want high-caffeine vs caffeine-free options.
Exercise 2: Order Processing System ⭐
Create an order processing system with simulated delays.
Create these functions:
1. validateOrder(order, callback) - 200ms delay
Check all teaIds exist in the teas array
Callback receives { valid: boolean, errors: string[] }
2. calculateTotal(order, callback) - 300ms delay
Sum up pricePerGram * grams for each item
Callback receives { orderId: number, total: number }
3. checkStock(order, callback) - 400ms delay
Check if each tea has enough stock for the order quantity
Callback receives { orderId: number, inStock: boolean, shortages: string[] }
Test each function individually with console.log as callback function to see results after delays:
You an test validateOrder like this:
Exercise 3: Sequential Processing
Using the functions from Exercise 2, process an order through all three steps in sequence :
If valid, calculate total
If total calculated, check stock
This requires "callback nesting" - calling the next function inside the previous callback.
💡 This nesting is ugly and hard to read. It's called "callback hell." Week 3 will show how Promises solve this!
Exercise 4: Inventory Aggregation from File
Create a file inventory-updates.json:
Write a function that:
Reads this file using a callback
Uses reduce to calculate net change per tea
Combines with original tea data to show new stock levels
Expected output format:
Exercise 5: Build runSequentially ⭐⭐
Create a utility function that runs delayed operations in sequence:
Test it:
Expected output (in order, despite different delays):
💡 This is challenging! Hint: use recursion or track an index. Each task's done callback should trigger the next task.
Create a folder week2-assignment/ with:
exercise4.js + inventory-updates.json
Each file should be runnable with node exerciseN.js.