shuffle.js

  1. import isArray from './isArray';
  2. import randomInt from './randomInt';
  3. /**
  4. * 创建一个被打乱的数组。使用 [Fisher-Yates shuffle](https://en.wikipedia.org/wiki/Fisher%E2%80%93Yates_shuffle) 版本。
  5. *
  6. * @alias module:Array.shuffle
  7. * @since 1.0.0
  8. * @param {Array} array 要打乱的数组。
  9. * @returns {Array} 打乱的数组。
  10. * @example
  11. *
  12. * shuffle([1, 2, 3, 4]); // [2, 4, 3, 1]
  13. *
  14. * shuffle([1, 2, 3, 4]); // [3, 2, 1, 4]
  15. *
  16. */
  17. function shuffle(array) {
  18. if (!isArray(array) || array.length < 1) {
  19. return [];
  20. }
  21. const result = array.slice();
  22. const length = result.length;
  23. const lastIndex = length - 1;
  24. let index = -1;
  25. while (++index < length) {
  26. const rand = randomInt(index, lastIndex);
  27. const value = result[rand];
  28. result[rand] = result[index];
  29. result[index] = value;
  30. }
  31. return result;
  32. }
  33. export default shuffle;