JS Built-ins
DesignPatternsadvanced

Strategy β€” Multiple strategy instances

πŸ“– Usage Example
const stratA = { sort: arr => [...arr].sort() };
const stratB = { sort: arr => [...arr].sort((a, b) => b - a) };
[stratA, stratB].forEach(s => console.log(s.sort([3, 1, 2])));

Bundle strategies as objects with a common interface for clean interchangeability.

Strategy Pattern β€” Different Strategy Instances

Two different Sorter instances with different strategies should produce different results.

Challenge: Create two Sorter instances with different strategies. Verify they sort the same array differently.

Example:

const ascending = (a, b) => a - b
const descending = (a, b) => b - a
const s1 = new Sorter(ascending)
const s2 = new Sorter(descending)
s1.sort([3, 1, 2]) // [1, 2, 3]
s2.sort([3, 1, 2]) // [3, 2, 1]
πŸ’‘ Hints (3)
  • β€’ Each Sorter instance stores its own strategy
  • β€’ Different strategies produce different results
  • β€’ Instances are independent