Clients often want a list in a useful order: the cheapest products first, or names from A to Z. An array's sort method puts it in order. It can't compare two objects by itself, though, so you give it a compare function: a function that takes two items, a and b, and returns a number. A negative number means a comes first, a positive one means b comes first.
interface Review {
user: string;
stars: number;
}
function byStars(a: Review, b: Review): number {
return a.stars - b.stars;
}
const reviews: Review[] = [{ user: "ana", stars: 5 }, { user: "bo", stars: 3 }];
reviews.sort(byStars);
// [{ user: "bo", stars: 3 }, { user: "ana", stars: 5 }]
Write byStars without parentheses: you hand over the function itself, and sort calls it on pairs of items. TypeScript checks that it fits: reviews is a Review[], and byStars takes two Review values and returns a number. sort changes the order of the array it is called on, so sort a new array when the original must keep its order. Text can't be subtracted: a.localeCompare(b) compares two strings in alphabetical order and gives a negative number when a comes first.
The client picks the order with a query parameter: ?sort=price or ?sort=name. Any other value is a mistake, so the shop answers 400 with an error. Without sort, the list keeps the shop's order, and the filters still work. The lists below show product names only; each item is a full product.
GET /products?sort=price → 200 [Pen, Notebook, Mug, Lamp]
GET /products?sort=name → 200 [Lamp, Mug, Notebook, Pen]
GET /products → 200 [Mug, Notebook, Lamp, Pen]
GET /products?category=office&sort=price → 200 [Pen, Notebook]
GET /products?sort=color → 400 {"error": "Sort must be price or name"}
Your task: write two compare functions, byPrice and byName, each taking two Product values and returning a number. In GET /products, read sort, answer 400 for an unknown sort, and sort the filtered list by price or by name.
Assignment
Follow the Coding Tutorial to add sorting to GET /products.
Hint
Sort after the filter loop, so only the products that passed the filters get sorted. Give sort the compare function by its name, without parentheses.
Free plan: 30 tutor messages. PRO is unlimited.
