Select interchangeable behavior with a strategy
Quick answer
A strategy is a callable implementation of a shared behavior contract. Choose the strategy from a known set and pass it to the operation that needs it, rather than hard-coding policy decisions across the application.
How it works
For example, standard and express shipping policies can both accept a quantity and return a fee in integer credits. A Map maps known names to strategy functions. Reject unknown policy names or define an explicit fallback. Do not invoke an arbitrary property obtained from external text. When only one small condition exists, a simple conditional may be clearer than a pattern.
Local examples
Run in Node.js v22.16.0 as a CommonJS script. Actual ByteMind editor support is unverified.
(async () => {const fees=new Map([["standard",n=>n+2],["express",n=>n*2+3]]);const fee=(name,n)=>fees.has(name)?fees.get(name)(n):null;console.log(fee("standard",4),fee("express",4),fee("other",4));})()Expected console output:
6 11 nullBoth known policies return a fee and an unknown name is rejected.
Run in Node.js v22.16.0 as a CommonJS script. Actual ByteMind editor support is unverified.
(async () => {const quote=(n,fee)=>n*5+fee(n);console.log(quote(3,n=>2),quote(3,n=>n));})()Expected console output:
17 18Only the configured fee behavior changes; the base calculation remains the same.
Common mistakes
Do not give interchangeable strategies incompatible result units or signatures. Validate the selector before calling a strategy.
Practice
Create two fee policies with one shared input and output contract. Test both and one unknown policy name.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Select interchangeable behavior with a strategy — Knowledge Check
Apply the concept and reason about local example output.
What makes two fee strategies interchangeable?
How should a strategy registry handle an unknown input name?
When might a strategy abstraction be unnecessary?
What is the exact console output in Select interchangeable behavior with a strategy example 1?
(async () => {const fees=new Map([["standard",n=>n+2],["express",n=>n*2+3]]);const fee=(name,n)=>fees.has(name)?fees.get(name)(n):null;console.log(fee("standard",4),fee("express",4),fee("other",4));})()What is the exact console output in Select interchangeable behavior with a strategy example 2?
(async () => {const quote=(n,fee)=>n*5+fee(n);console.log(quote(3,n=>2),quote(3,n=>n));})()