pick.js 802 B

12345678910111213141516171819202122232425262728293031
  1. var randInt = require('../random/randInt');
  2. /**
  3. * Remove random item(s) from the Array and return it.
  4. * Returns an Array of items if [nItems] is provided or a single item if
  5. * it isn't specified.
  6. */
  7. function pick(arr, nItems){
  8. if (nItems != null) {
  9. var result = [];
  10. if (nItems > 0 && arr && arr.length) {
  11. nItems = nItems > arr.length? arr.length : nItems;
  12. while (nItems--) {
  13. result.push( pickOne(arr) );
  14. }
  15. }
  16. return result;
  17. }
  18. return (arr && arr.length)? pickOne(arr) : void(0);
  19. }
  20. function pickOne(arr){
  21. var idx = randInt(0, arr.length - 1);
  22. return arr.splice(idx, 1)[0];
  23. }
  24. module.exports = pick;