Home > Net >  How to use logical or operator with multiple values?
How to use logical or operator with multiple values?

Time:04-06

How to simplify the code when using multiple or operators. I have a list of numbers from 0 to 6 separated by logical or.Is there any way to simplify it?

if (filteredMnth === 'mnth') {
         
  return (new Date(exp?.date).getMonth().toString() === "0" || "1" || "2" || "3" || "4" || "5" || "6"   )

}

CodePudding user response:

A nice pattern for this, is to create an Array of valid or accepted values and use the Array.prototype.includes to check for one from the user input:

const validValues = [ 0, 1, 2 ];
const input = 2;

validValues.includes(input);
// => true

const input2 = 3;

validValues.includes(input2);
//=> false

As @Robby Cornelissen already mentioned in the comment, in your case it really does not make any sense, but I'm including this pattern here to answer a more generic version of your question.

CodePudding user response:

first be carefull

(month === "0" || "1" || "2" || "3" || "4" || "5" || "6" || "7" || "8" || "9" || "10" || "11")

will not return a boolean but if month is not equal to 0 it will return "1"

function wrongValidateMonth(month) {
  return (month === "0" || "1" || "2" || "3" || "4" || "5" || "6" || "7" || "8" || "9" || "10" || "11")
}

console.log(wrongValidateMonth("0"));
console.log(wrongValidateMonth("1"));

An idea can be to construct an array of all valid month number and look if month is includes in this array

function runningValidateMonth(month) {
  let monthList = Array.from(Array(12).keys());
  return (monthList.some(oneMonth => oneMonth.toString() === month));
}


console.log(runningValidateMonth("0"));
console.log(runningValidateMonth("1"));
console.log(runningValidateMonth("25"));

CodePudding user response:

Since you are having multiple values you can make use of List and includes method as below

const validMonths = ["1", "2", ...]
const monthToCheck = new Date(exp?.date).getMonth().toString()
if(validMonths.includes(monthToCheck)){
    //Evaluates true if value exist
}
  • Related