JS Built-ins
DesignPatternsbeginner

Strategy β€” Descending sort

πŸ“– Usage Example
const desc = (a, b) => b - a;
sorter([3, 1, 2], desc); // [3, 2, 1]

Pass a descending comparator to change sorting behavior without changing the sorter.

Strategy Pattern β€” Different Sorting Strategy

The same Sorter class can use a different strategy to sort in descending order.

Challenge: Implement a Sorter class that works with both ascending and descending strategies.

Example:

const ascending = (a, b) => a - b
const descending = (a, b) => b - a
const asc = new Sorter(ascending)
const desc = new Sorter(descending)
asc.sort([3, 1, 2]) // [1, 2, 3]
desc.sort([3, 1, 2]) // [3, 2, 1]
πŸ’‘ Hints (3)
  • β€’ Create two different strategies
  • β€’ Pass different strategies to Sorter instances
  • β€’ Same Sorter class works with both