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

84
Visualizações
Recode by not using conditional

The below function works good by if statements , I want the same functionality by using without condition statements.

Hello(x){
    If(x<0){
       Console.log("greater");
    }Else{
       Console.log("smaller");
    }
};

Hello(1);
Hello(-1);
about 4 years ago · Juan Pablo Isaza
3 Respostas
Responde à pergunta

0

You could use an Object but it's odd. An if...else statement or it's shorter ternary form more clearly conveys the logic at play which is always preferable.

function Hello(x) {
  const lt = {
    true: "smaller",
    false: "greater"
  };

  console.log(lt[x < 0]);
};

Hello(1);
Hello(-1);

about 4 years ago · Juan Pablo Isaza Relatório

0

This is probably a stupid thing to actually do and might be overly specific to your example but...:

const hello = (x) => {
  const lt = x < 0;
  console.log("greater".repeat(lt) + "smaller".repeat(1 - lt));
};

hello(-1);
hello(1);

Borrowing from @Teemu's comment a slightly more flexible thing could be:

const if_else = (cond_fn, if_fn, else_fn = (x) => x) =>
  [else_fn, if_fn][+cond_fn()]();

const hello = (x) =>
  if_else(
    () => x < 0,
    () => console.log('greater'),
    () => console.log('smaller')
  );

hello(-1);
hello(1);

about 4 years ago · Juan Pablo Isaza Relatório

0

@Teemu explained how to do it without branching, and there are times where that can be beneficial (example: Why is processing a sorted array faster than processing an unsorted array?).

function hello(x) {
  console.log(['greater', 'smaller'][+(x < 0)]);
}

hello(1);
hello(-1);

but by definition you cannot achieve behavior based on a condition without a conditional.

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