Skip to content

Instantly share code, notes, and snippets.

@sackeyjason
Last active August 13, 2021 12:24
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sackeyjason/2eecb96fcafc0bfcfd5c76efde6d4bce to your computer and use it in GitHub Desktop.
Save sackeyjason/2eecb96fcafc0bfcfd5c76efde6d4bce to your computer and use it in GitHub Desktop.
Shuffle array
/**
* Randomise array order
* @param {Array} arr Array to randomise
* @param {Object} [options]
* @param {Boolean} [options.mutate] Sets if should modify given array. Defaults to false
* @param {Function} [options.rand] Randomly generate an integer j: min <= j < max
* @returns {Array}
*/
const shuffle = (arr, options) => {
const len = arr.length;
const { rand, mutate } = {
rand: (min, max) => Math.floor(Math.random() * (max - min) + min),
mutate: false,
...options,
};
const list = mutate ? arr : [...arr];
for (let i = 0; i < len; ++i) {
const j = rand(i, len);
[list[i], list[j]] = [list[j], list[i]];
}
return list;
};
// https://en.wikipedia.org/wiki/Fisher%E2%80%93Yates_shuffle
// See also
// - https://github.com/pazguille/shuffle-array/blob/master/index.js
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment