snazzybouche
snazzybouche

Reputation: 2424

What's the easiest way to use a switch statement when I don't know how many things need to be compared against?

So I have a terminal into which the user types commands.

I take the first phrase of the command and run it through a switch statement to work out what to do.

switch(phrases[0]) {
    case "boot":
        // Do something
        break;
    case "switch":
    case "app":
    case "change":
    case "switchapp":
    case "changeapp":
        // Do something
        break;
    case "help":
        // Do something
        break;
    case "wipe":
    case "erase":
    case "restart":
    case "forget":
    case "clear":
    case "undo":
        // Do something else here
        break;
    default:
        throw new Error("Unknown command: " + phrases[0]);
}

Note that for each command I've got a few alternatives to make it more likely for the user to pick a correct command on their first try.

However - if I have all of those alternatives in an array instead of hard-coded into the switch function, how do I access them?

I've considered using if/else combined with .some() but that seems clunky:

if(bootCommands.some(function(name){return name == phrases[0]}))
    // Do something
if(switchCommands.some(function(name){return name == phrases[0]})) {
    // Do something
} else if(helpCommands.some(function(name){return name == phrases[0]})) {
    // Do something
} else if(wipeCommands.some(function(name){return name == phrases[0]})) {
    // Do something
} else {
    throw new Error("Unknown command: " + phrases[0]);
}

There's an easier way, surely?

Upvotes: 0

Views: 37

Answers (1)

Satpal
Satpal

Reputation: 133453

You can still use switch-case expression with Array.includes()

switch(true) {
    case bootCommands.includes(phrases[0]):
        // Do something
        break;
    case wipeCommands.includes(phrases[0]):
        // Do something
        break;
    default:
        throw new Error("Unknown command: " + phrases[0]);
}

var bootCommands = ["boot"],
  wipeCommands = ["wipe", "erase", "restart", "forget", "clear", "undo"],
  command = "restart";



switch (true) {
  case bootCommands.includes(command):
    // Do something
    console.log("Boot command: " + command);
    break;
  case wipeCommands.includes(command):
    // Do something
    console.log("Wipe command: " + command);
    break;
  default:
    console.log("Unknown command: " + command);
}

Upvotes: 1

Related Questions