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

409
Visualizações
Switch case version of if(input.startsWith("string")) { ... } in JavaScript

Context: I am making a game that has a command handler. And inside that command Handler, i am trying to optimize a section of the code.

I am trying to make a switch-case statement that allows me to do the exact same thing as the one shown below

input.startsWith('echo') ? ( History.add(input), commands.echo(input) ) 
: ( input.startsWith('history') ? (History.add(input), commands.history(input))
: input.startsWith("new") ? (History.add(input), commands.new(input) ) 
: input.startsWith('theme') ? (History.add(input), commands.theme(input)) 
: (developerMode == true && input == "test") ? (History.add(input), commands.test()) 
: input.startsWith("cd") ? (History.add(input), commands.cd(input))
: input.startsWith("find") ? (History.add(input), commands.find(input, type, title)) 
: (History.add(input), utils.message({ user: '$', command: input }, ` - bash: ${input}: command not found `, 'error')))

SIMPLIFIED VERSION:

if (input.startsWith('echo')) {
    History.add(input)
    commands.echo(input);
} else if (input.startsWith("history"))
    History.add(input)
    commands.history(input);
} else if (input.startsWith("new")) {
    History.add(input)
    commands.new(input);
} else if (input.startsWith('theme')) {
    History.add(input)
    commands.theme(input);
} else if (developerMode == true && input == "test") {
    History.add(input)
    commands.test()
} else if (input.startsWith("cd")) {
    History.add(input)
    commands.cd(input)
} else if (input.startsWith("find")) {
    History.add(input)
    commands.find(input, type, title)
} else {
    History.add(input)
    utils.message({ user: '$', command: input }, ` - bash: ${input}: command not found `, 'error');
} 
over 4 years ago · Santiago Trujillo
1 Respostas
Responde à pergunta

0

There is some redundency in your code. First, you can check if your command is a valid command by doing a test on commands's keys (you should tryi to get the first command arguments without string#startWith).

As stated in a comment, you don't need to change a else-if to a switch. There is no gain. But, in both cases, you will have to add code to handle your commands, both to populate your command object AND to parse the user input.

To get some flexibility and reusability, the best you can do is to parse and execute all your commands in the same way.

Assuming that your commands are separated by whitespaces, there is a way to go :


const [ cmd, ...args ] = input.split(' ');//at index 0, you get your command, in args, you get your command args. It's called array destructuring
//Note that you may need a more complexe way to parse your command, but you should get the idea.

//Since you do it every time, you don't have to repeat it
History.push(input);

if(cmd in commands) commands[cmd](input, ...args);
else utils.message(
    { user: '$', command: input }, 
    ` - bash: ${input}: command not found `, 'error'
);

over 4 years ago · Santiago Trujillo 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