JS Built-ins
DesignPatternsintermediate

Strategy β€” Runtime strategy swap

πŸ“– Usage Example
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.

Strategy Pattern β€” Changing Strategy at Runtime

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]
πŸ’‘ Hints (4)
  • β€’ Initialize strategy to null or undefined
  • β€’ Add setStrategy method
  • β€’ Update this.strategy in setStrategy
  • β€’ Use current strategy in sort