let strategy = (a, b) => a - b;
function sort(arr) { return [...arr].sort(strategy); }
// change strategy at runtime:
strategy = (a, b) => b - a;Swap the strategy variable at runtime to change behavior without modifying calling code.
The strategy can be changed after the Sorter is created.
Challenge: Implement a Sorter class with a setStrategy(strategy) method to change the sorting algorithm at runtime.
Example:
const sorter = new Sorter()
sorter.setStrategy((a, b) => a - b)
sorter.sort([3, 1, 2]) // [1, 2, 3]
sorter.setStrategy((a, b) => b - a)
sorter.sort([3, 1, 2]) // [3, 2, 1]