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.
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]