Assignment

Complete these exercises after the session. They build on callbacks, delayed execution, and reduce.

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:

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:

  1. First validate

  2. If valid, calculate total

  3. If total calculated, check stock

  4. Log final result

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:

  1. Reads this file using a callback

  2. Uses reduce to calculate net change per tea

  3. Combines with original tea data to show new stock levels

  4. Logs a report

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.


Submission

Create a folder week2-assignment/ with:

  • exercise1.js

  • exercise2.js

  • exercise3.js

  • exercise4.js + inventory-updates.json

  • exercise5.js

Each file should be runnable with node exerciseN.js.

Last updated