casual icon indicating copy to clipboard operation
casual copied to clipboard

Random elements from array

Open ghost opened this issue 7 years ago • 2 comments

What about adding a casual.random_element(array, x) to return x random elements from array?

Under the hood code could look like:

function getRandomArrayElements (array, count, startIndex, endIndex) {
  if (Array.isArray(array) === false) throw new Error('Invalid array object')
  if (startIndex < 0 || startIndex > array.length - 1) throw new Error('Invalid startIndex value')
  if (endIndex < 0 || endIndex > array.length - 1) throw new Error('Invalid endIndex value')
  if (count < startIndex || count > (endIndex - startIndex) + 1) throw new Error('Invalid count value')
  var resultList = []
  var temp, randomIndex
  while (count > 0) {
    randomIndex = chooseRandomNumer(startIndex, endIndex)
    temp = array[randomIndex]
    array[randomIndex] = array[endIndex]
    array[endIndex] = temp
    resultList.push(temp)
    count--
    endIndex--
  }
  return resultList
}

Just submitting the idea for validation, will come back with a PR if validated.

ghost avatar Mar 24 '17 10:03 ghost

There is random_element function, not sure if random_elements is necessary. But if more other people would find it useful we can add it.

boo1ean avatar Mar 30 '17 09:03 boo1ean

I use it with my ORM (sequelize) to create data seeders.
It's nice to have when you need to create random N:M associations.

ghost avatar Mar 30 '17 09:03 ghost