array.js 1020 B

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  1. 'use strict';
  2. /**
  3. * Array random slice with items count.
  4. * @param {Array} arr
  5. * @param {Number} num, number of sub items.
  6. * @return {Array}
  7. */
  8. exports.randomSlice = function randomSlice(arr, num) {
  9. if (!num || num >= arr.length) {
  10. return arr.slice();
  11. }
  12. var index = Math.floor(Math.random() * arr.length);
  13. var a = [];
  14. for (var i = 0, j = index; i < num; i++) {
  15. a.push(arr[j++]);
  16. if (j === arr.length) {
  17. j = 0;
  18. }
  19. }
  20. return a;
  21. };
  22. /**
  23. * Remove one exists element from an array
  24. * @param {Array} arr
  25. * @param {Number} index - remove element index
  26. * @return {Array} the array instance
  27. */
  28. exports.spliceOne = function spliceOne(arr, index) {
  29. if (index < 0) {
  30. index = arr.length + index;
  31. // still negative, not found element
  32. if (index < 0) {
  33. return arr;
  34. }
  35. }
  36. // don't touch
  37. if (index >= arr.length) {
  38. return arr;
  39. }
  40. for (var i = index, k = i + 1, n = arr.length; k < n; i += 1, k += 1) {
  41. arr[i] = arr[k];
  42. }
  43. arr.pop();
  44. return arr;
  45. };