Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Random elements from array #62

Open
ghost opened this issue Mar 24, 2017 · 2 comments
Open

Random elements from array #62

ghost opened this issue Mar 24, 2017 · 2 comments

Comments

@ghost
Copy link

ghost commented Mar 24, 2017

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.

@boo1ean
Copy link
Owner

boo1ean commented Mar 30, 2017

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.

@ghost
Copy link
Author

ghost commented Mar 30, 2017

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant