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