Start learning free

LESSON 12 OF 173 · BACKEND: HOW THE WEB WORKS

Project: A Restock Report

Practice

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 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:

function byPrice(a, b) {
  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 and API_KEY are given. 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 = {}. In the loop, compare stock[product.id] with 10 using <. Call prices.sort(byName) just before the loop, with no parentheses after byName.


STEP 1 OF 12
    Ctrl + Enter to check