Last active
August 13, 2021 12:24
-
-
Save sackeyjason/2eecb96fcafc0bfcfd5c76efde6d4bce to your computer and use it in GitHub Desktop.
Shuffle array
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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