Skip to content

Commit

Permalink
refactor: early return in fallback behavior
Browse files Browse the repository at this point in the history
Fallback behavior should use early returns rather than else...if.
Using early returns instead makes it possible to include looping logic
without as many changes to the code.

For example, we can now add such a thing:

  for ( const provider of providers ) {
    const maybe_command = provider[cmd];
    if ( ! maybe_command ) continue;
    return maybe_command();
  }

Since the fact of whether or not this loop will find the command is
determined by the outcome, rather than a conditional expression, it
would be non-trivial to include it in the else...if chain.
  • Loading branch information
KernelDeimos committed Feb 6, 2025
1 parent f0cf652 commit 298d3ac
Showing 1 changed file with 12 additions and 7 deletions.
19 changes: 12 additions & 7 deletions src/executor.js
Original file line number Diff line number Diff line change
Expand Up @@ -163,7 +163,9 @@ export async function execCommand(input) {
// Handle help command
const command = args[0];
showHelp(command);
} else if (cmd.startsWith('!')) {
return;
}
if (cmd.startsWith('!')) {
// Execute the command on the host machine
const hostCommand = input.slice(1); // Remove the "!"
exec(hostCommand, (error, stdout, stderr) => {
Expand All @@ -178,17 +180,20 @@ export async function execCommand(input) {
console.log(stdout);
console.log(chalk.green(`Press <Enter> to return.`));
});
} else if (commands[cmd]) {
return;
}
if (commands[cmd]) {
try {
await commands[cmd](args);
} catch (error) {
console.error(chalk.red(`Error executing command: ${error.message}`));
}
} else {
if (!['Y', 'N'].includes(cmd.toUpperCase()[0])) {
console.log(chalk.red(`Unknown command: ${cmd}`));
showHelp();
}
return;
}

if (!['Y', 'N'].includes(cmd.toUpperCase()[0])) {
console.log(chalk.red(`Unknown command: ${cmd}`));
showHelp();
}
}

Expand Down

0 comments on commit 298d3ac

Please sign in to comment.