Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

213
Visualizações
Javascript use strategy pattern to remove if else and switch

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"
        }
    }
}
about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

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]);
about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda