Set condition that keeps right number input

I need to make an IF in JS code. There are some conditions for the number input:

  • allowed numbers: 1, 2, 34, 68, 136, 272, 544
  • numbers 545 and above is allowed only when number%5 == 0
  • max allowed number is 4000

Is there any easy way how to put these condition into just one IF?

Thank you for the answer.

1 thought on “Set condition that keeps right number input”

  1. We can create a function to test the values, testNumber with one if statement, by using Array.includes to test the number and then checking if the value is between 545 and 4000 and is divisible by 5.

    /* Number must be one of [1, 2, 34, 68, 136, 272, 544] OR be between
       545 and 4000 and divisible by 5 */
    function testNumber(n) {
        const allowedNumbers = [1, 2, 34, 68, 136, 272, 544];
        return ((allowedNumbers.includes(n)) || ((n <= 4000) && (n >= 545) && (n % 5 === 0)));
    }
    
    const testValues = [ 
     { n: 1, expectedResult: true},
     { n: 34, expectedResult: true},
     { n: 4000, expectedResult: true},
     { n: 0, expectedResult: false},
     { n: 546, expectedResult: false},
     { n: 4001, expectedResult: false},
    ];
    
    console.log(`All ${testValues.length} tests pass:`, testValues.every(({n, expectedResult}) => testNumber(n) === expectedResult))
    Reply

Leave a Comment