skip to Main Content

I have this function. It works fine. Is there a way to shorten the logic though?

function doNotDuplicateRandomIndex() {
  if (randomIndex === 0 || randomIndex === 1 || randomIndex === 2 || randomIndex ===3) {
    createRandomIndex();
  }
}

I haven’t tried anything else, simply because I don’t know where to start.

3

Answers


  1. Use .includes():

    function doNotDuplicateRandomIndex() {
      if ([0,1,2,3].includes(randomIndex)){
        createRandomIndex();
      }
    }
    
    Login or Signup to reply.
  2. Use the Less than (<) operator. You’re welcome.

    function doNotDuplicateRandomIndex() {
      if (randomIndex < 4) {
        createRandomIndex();
      }
    }
    

    In fact, this can be even shorter by removing the brackets from the if...else statement.

    See: Are braces necessary in one-line statements in JavaScript?

    function doNotDuplicateRandomIndex() {
      if (randomIndex < 4) createRandomIndex();
    }
    

    Insane, we can make the whole function even shorter by converting it to an arrow function expression.

    The if...else statement is replaced with a Logical AND (&&) operator.

    const doNotDuplicateRandomIndex = () => randomIndex < 4 && createRandomIndex();
    

    Nice answer by XMehdi01, the same concept can be converted to an arrow function expression too.

    const doNotDuplicateRandomIndex = () => [0, 1, 2, 3].includes(randomIndex) && createRandomIndex();
    
    Login or Signup to reply.
  3. I like the other answer, but in your case I think you could use an object or map to check whether an id is used:

    const usedIds = {};
    usedIds['1234-1234'] = true;
    
    function doNotDuplicateRandomIndex() {
      if (typeof usedIds[id] === 'undefined') {
        createRandomIndex();
      }
    }
    

    you could also use Map.prototype.has

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search