3

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.

gard
  • 33
  • 5

3 Answers3

5

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();
  • 1
    If the index could have negative values (as in `array.at(-1)`, for example), `<` would be unsuitable. – InSync Jul 03 '23 at 22:54
  • Quite true, I've to admit, but that's something that's not included in the question, and I think I don't have to predict the future of what the OP is going to do with the function later, am I wrong? Anyway, +1 @InSync – Sally loves Lightning Jul 03 '23 at 22:57
  • If I were to worry about specific negative values, I’d go with .include. But since I am not worried about that, this is certainly the best answer. Especially boiling it down to one line. I’m impressed. Thanks! – gard Jul 05 '23 at 01:37
  • @gard You're welcome. Glad to help :-) – Sally loves Lightning Jul 05 '23 at 01:38
3

Use .includes():

function doNotDuplicateRandomIndex() {
  if ([0,1,2,3].includes(randomIndex)){
    createRandomIndex();
  }
}
XMehdi01
  • 5,538
  • 2
  • 10
  • 34
  • I love this answer because .includes could be used for so much. I can’t mark it as the best answer though, simply because I think the <4 logic is easier to edit if I need to check for numbers 1-7 or something else. The precision of .includes is super useful though, and I’ll likely use that in a lot of places. Thanks! – gard Jul 05 '23 at 01:35
  • My answer `.includes()` could handle the case where you want to verify numbers that are not consecutive like `1, 10, 8`, you can't do that with logic of ` – XMehdi01 Jul 05 '23 at 08:11
1

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

neaumusic
  • 10,027
  • 9
  • 55
  • 83