JS Built-ins
DesignPatternsbeginner

Strategy β€” Ascending sort

πŸ“– Usage Example
function sorter(data, strategy) {
  return [...data].sort(strategy);
}
const asc = (a, b) => a - b;
sorter([3, 1, 2], asc); // [1, 2, 3]

The Strategy pattern swaps algorithms at runtime by passing them as parameters.

Strategy Pattern β€” Sorting Strategies

The Strategy pattern allows swapping algorithms at runtime. Here, different sorting strategies can be plugged in.

Challenge: Implement a Sorter class that accepts a strategy (a comparison function) and uses it to sort an array in ascending order.

Example:

const ascending = (a, b) => a - b
const sorter = new Sorter(ascending)
sorter.sort([3, 1, 2]) // [1, 2, 3]
πŸ’‘ Hints (3)
  • β€’ Store strategy in constructor
  • β€’ Use the strategy function in sort
  • β€’ Use slice to avoid mutating original array