简体   繁体   中英

Is there a simple way to condense if statements into a function to check arguments?

I have a switch statement for handling commands, and it works as intended. However, I also have tons of commands/cases. The error checking is to make sure that the program won't crash if they type something that isn't a number. Is there a way to condense those if statements into a function somehow?

case "test":
        if (typeof args[1] === 'string') 
        {
            args[1] = parseInt(args[1])
            Functions.packs = args[1];
        }
        else if(Number.isNaN(+args[1]))
        {
            message.reply("The command was invalid.");
            break;
        }
        else
        {
            message.reply("The command was invalid.");
            break;
        }

This is currently what the start of every command looks like, and it is becoming tedious to check commands. I have tried making a function for it, but nothing I tried has worked, so I doubt I'm on the right track.

I would attempt to use.toString() to force everything to be string and then parseInt() the result. Allows you to just test for NaN...

var numberTest = function(testArg){
  var testString = testArg.toString();
  var testNumber = parseInt(testString);
  var returnObj = {
    number: testNumber,
    valid: Number.isNaN(testNumber)
  };
  return returnObj;
}

case "test":
  var argTest = numberTest(args[1]);
  if(argTest.valid){
    Functions.packs = argTest.number;
  }
  else{
    message.reply("The command was invalid.");
  }
  break;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM