casual
casual copied to clipboard
Random elements from array
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.
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.
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.