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

Viewed 57

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.

1 Answers

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;
Related