This project puts the whole module together. The shop wants a restock report: every product the supplier has fewer than 10 of, with its stock and its price, sorted by name. No single answer has all of that. /prices has the names and prices, and /stock has the counts, but only if you send the X-Api-Key header.
Joining two answers: both arrays use the same id for a product, and that is the only thing that links them. Turn the stock array into an object of type { [id: number]: number } that maps each id to its count. Then stock[product.id] gives any product's stock in one step, with no searching.
Sorting objects: sort() alone can't order an array of objects, because it doesn't know what to compare. Give it a compare function: it takes two items, a and b, and returns a negative number when a goes first and a positive one when b does. For example, to sort a cart by price:
interface Item {
name: string;
price: number;
}
function byPrice(a: Item, b: Item): number {
return a.price - b.price;
}
cart.sort(byPrice);
Pass the function without parentheses: sort calls it on pairs of items for you. Strings can't be subtracted, so for two strings use localeCompare: "Lamp".localeCompare("Notebook") is negative, because Lamp comes first in the alphabet. Your script must print exactly these lines:
Lamp: 8 left, price 14
Notebook: 0 left, price 3
Plant: 0 left, price 6
Your task: SUPPLIER, API_KEY and the interfaces Price and StockItem are given. Inside main, read /prices, read /stock with the key, build the object stock from id to count, then print every product with fewer than 10 left, sorted by name: its name with a colon, its stock, left, price and its price.
Assignment
Follow the Coding Tutorial to build the restock report: two requests, an object of stock by id, the printing loop and a sort by name.
Hint
Build stock before the loop, starting from const stock: { [id: number]: number } = {}. In the loop, compare stock[product.id] with 10 using <. Call prices.sort(byName) just before the loop, with no parentheses after byName.
Free plan: 30 tutor messages. PRO is unlimited.
