JS Built-ins
DesignPatternsintermediate

Strategy β€” Custom comparator

πŸ“– Usage Example
const byName = (a, b) => a.name.localeCompare(b.name);
const byAge = (a, b) => a.age - b.age;
const users = [{ name: 'Bob', age: 30 }, { name: 'Alice', age: 25 }];
users.sort(byName); // Alice first

Custom comparator strategies let you sort objects by any property.

Strategy Pattern β€” Sorting Objects by Property

Strategies can be used to sort complex objects based on specific criteria.

Challenge: Create a Sorter that can sort objects using a strategy. Implement a strategy that sorts users by their age property in ascending order.

Example:

const users = [
  { name: 'Alice', age: 30 },
  { name: 'Bob', age: 25 },
]
const byAge = (a, b) => a.age - b.age
const sorter = new Sorter(byAge)
sorter.sort(users)
// [{ name: 'Bob', age: 25 }, { name: 'Alice', age: 30 }]
πŸ’‘ Hints (3)
  • β€’ Access properties within strategy function
  • β€’ Use a, b to compare objects
  • β€’ Return difference or comparison result