Assignment
Complete these exercises after the session. All exercises use the tea data.
import { teas } from "../data/teas.js";Exercise 1: Rewrite with Array Methods
This code uses a traditional for-loop. Rewrite it using filter and map with arrow functions:
const result = [];
for (let i = 0; i < teas.length; i++) {
if (teas[i].caffeineLevel !== "none") {
result.push(teas[i].name.toUpperCase());
}
}
console.log(result);Your solution should be 2-3 lines using chained array methods.
Exercise 2: Inventory Report ⭐
Build a function that generates an inventory report:
function inventoryReport(teas) {
return {
totalTeas: /* total number of teas */,
inStock: /* number of teas where inStock is true */,
outOfStock: /* number of teas where inStock is false */,
totalInventoryValue: /* sum of (pricePerGram * stockCount) for all teas */,
averagePrice: /* average pricePerGram across all teas */
};
}
console.log(inventoryReport(teas));Expected output structure:
Exercise 3: Low Stock Alert
Create a function that returns teas with low stock (less than 50 items):
Expected output format:
Exercise 4: Teas by Origin ⭐⭐
Create a function that groups teas by their origin country:
Expected output format:
Exercise 5: Search Function
Create a search function for the tea shop:
Hint: Use .toLowerCase() and .includes() for case-insensitive search.
Optional: reduce
These exercises use reduce. Try them if you want a challenge!
Exercise 6: Total Inventory Value (Optional)
Calculate the total value of all tea inventory using reduce:
Hint: reduce builds up a single value by processing each item. The 0 is your starting value.
Exercise 7: Count by Type (Optional)
Use reduce to count how many teas of each type exist:
Submission
Create a folder week1-assignment/ with:
exercise1.js- Rewrite with array methodsexercise2.js- Inventory reportexercise3.js- Low stock alertexercise4.js- Teas by originexercise5.js- Search functionexercise6.js- Total inventory value (optional)exercise7.js- Count by type (optional)
Each file should be runnable with node exerciseN.js.
Last updated