Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

406
Views
Cambiar la versión de mayúsculas y minúsculas de if(input.startsWith("string")) { ... } en JavaScript

Contexto: estoy creando un juego que tiene un controlador de comandos. Y dentro de ese controlador de comandos, estoy tratando de optimizar una sección del código.

Estoy tratando de hacer una declaración de cambio de caso que me permita hacer exactamente lo mismo que se muestra a continuación

 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')))

VERSIÓN SIMPLIFICADA:

 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 answers
Answer question

0

Hay cierta redundancia en su código. Primero, puede verificar si su comando es un comando válido haciendo una prueba en las teclas de los commands (debe intentar obtener los primeros argumentos del comando sin string#startWith).

Como se indica en un comentario, no necesita cambiar un else-if a un interruptor. No hay ganancia. Pero, en ambos casos, tendrá que agregar código para manejar sus comandos, tanto para completar su objeto de comando como para analizar la entrada del usuario.

Para obtener cierta flexibilidad y reutilización, lo mejor que puede hacer es analizar y ejecutar todos los comandos de la misma manera.

Suponiendo que sus comandos están separados por espacios en blanco, hay un camino a seguir:

 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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!