shuffleArray.js 971 B

1234567891011121314151617181920212223242526272829303132333435363738394041
  1. 'use strict';
  2. Object.defineProperty(exports, '__esModule', {
  3. value: true
  4. });
  5. exports.default = shuffleArray;
  6. exports.rngBuilder = void 0;
  7. var _pureRand = require('pure-rand');
  8. /**
  9. * Copyright (c) Meta Platforms, Inc. and affiliates.
  10. *
  11. * This source code is licensed under the MIT license found in the
  12. * LICENSE file in the root directory of this source tree.
  13. */
  14. // Generates [from, to] inclusive
  15. const rngBuilder = seed => {
  16. const gen = (0, _pureRand.xoroshiro128plus)(seed);
  17. return {
  18. next: (from, to) =>
  19. (0, _pureRand.unsafeUniformIntDistribution)(from, to, gen)
  20. };
  21. };
  22. // Fisher-Yates shuffle
  23. // This is performed in-place
  24. exports.rngBuilder = rngBuilder;
  25. function shuffleArray(array, random) {
  26. const length = array.length;
  27. if (length === 0) {
  28. return [];
  29. }
  30. for (let i = 0; i < length; i++) {
  31. const n = random.next(i, length - 1);
  32. const value = array[i];
  33. array[i] = array[n];
  34. array[n] = value;
  35. }
  36. return array;
  37. }