A real shop can have thousands of products, and a page often shows only a few. A client asks for that with a query parameter: ?limit=2 means "at most 2 products".
To keep the first few items of an array, use splice with only a position. items.splice(n) removes everything from position n to the end, so the first n items stay. If n is bigger than the array, nothing is removed and you keep the whole array.
const days = ["Mon", "Tue", "Wed", "Thu", "Fri"];
days.splice(10); // nothing at position 10 or after: no error
console.log(days); // all five days
days.splice(2); // removes position 2 and everything after it
console.log(days); // [ 'Mon', 'Tue' ]
Cut the list last, after filtering and sorting, so ?sort=price&limit=2 gives the two cheapest products. A limit of 0 or less makes no sense, so it gets 400. Without limit, the answer is the whole list, as before. The lists below show product names only.
GET /products?limit=2 → 200 [Mug, Notebook]
GET /products?sort=price&limit=2 → 200 [Pen, Notebook]
GET /products?category=office&limit=1 → 200 [Notebook]
GET /products?limit=10 → 200 [Mug, Notebook, Lamp, Pen]
GET /products?limit=0 → 400 {"error": "Limit must be 1 or more"}
GET /products?limit=-3 → 400 {"error": "Limit must be 1 or more"}
Your task: in GET /products, read limit as a number, answer 400 when it is less than 1, and cut the list to its first limit products.
Assignment
Follow the Coding Tutorial to add a limit to GET /products.
Hint
Read limit with Number(...), like maxPrice; Number.isInteger(limit) tells you whether there is one. Check it before the loop, and cut result just before res.json(result), after the sorting.
Free plan: 30 tutor messages. PRO is unlimited.
