Javascript - Conditionally selecting the condition of a while loop

Viewed 45

I need to fill an array with randomly selected elements until the array reaches an appointed length. The length of that array must be equal to the smallest of two lengths. We'll call them length_1 and length_2. So if length_1 < length_2, then use length_1, otherwise, use length_2. Note that both lengths are constant so the statement length_1 < length_2 will always give the same Boolean value.

The method I came up with to deal with that situation is to create a while loop which, at each turn, adds a new randomly selected element to the array. It goes like this:

while (
length_1 < length_2
  ? array.length < length_1
  : array.length < length_2
  ) {
    // Add a new randomly selected element to the array
     };

Is this a valid way to it? Is there a more concise way to go about it?

2 Answers

You could get the minimum in advance for a looping condition.

const
    length = Math.min(length_1, length_2);

while (array.length < length) {
    // ...
}

I try to avoid while loops. They are prone to get into an endless loop.

const length = Math.min(length_1, length_2);

for(let i = 0; i < length; i+=1) {
  //...
}
Related