Reputation: 890
In Javascript, when we use if else or switch, if the value is a string value, we can use a strategy pattern to remove if else or switch by object[key]
:
const strategies = {
strategyA: ()=> { console.log("strategyA") },
strategyB: ()=> { console.log("strategyB") }
}
Say here I have two strategies, A and B and I can run by strategies[strategyValue]()
But how can I set the strategy if it's not a string? For example, in Fn1, the value is undefined
or test
or the rest; and in Fn2, I have the value with other value.
With these senarios, I cannot use object[key]
way. How can I convert these to the strategies pattern?
const Fn1 = (value) => {
const initValue = ""
if (!value) return initValue
if (value === "test") {
return {
test: "test",
}
}
return {
otherCondition: "otherCondition",
}
}
const Fn2 = (value) => {
switch (value) {
case 1: {
return 'a1'
}
case 2: {
return 'c2'
}
case 3: {
return 'b3'
}
default: {
return "other value"
}
}
}
Upvotes: 0
Views: 444
Reputation: 1277
Normally you would inject the strategy that should be used based on input or configuration. When should Fn2 be used instead of Fn1?
const Fn1 = (value) => {
...
}
const Fn2 = (value) => {
...
}
const doSomethingWithStrategy = (value, strategyCallback) => {
return strategyCallback(value);
}
const valueForStrategy = 1;
const strategy = (valueForStrategy instanceof String) ? Fn1 : Fn2;
doSomethingWithStrategy(valueForStrategy, strategy);
Since you're using functions you could also implement the condition in the strategies itself and chain/loop them
const Fn1 = (value) => {
if (value instanceof Number) {
return false;
}
...
}
const Fn2 = (value) => {
...
}
const doSomethingWithStrategies = (value, strategyCallbacks) => {
for (let index = 0; index < strategyCallbacks.length; index++) {
const returnValue = strategyCallbacks[index](value);
if (returnValue) {
return returnValue;
}
}
}
doSomethingWithStrategies(1, [Fn1, Fn2]);
Upvotes: 1