vrandom
Version:
an easy way to work with random numbers in javascript
27 lines (22 loc) • 682 B
JavaScript
/**
* Makes a shallow copy of `array` to prevent the argument from being mutated.
* @template {unknown} T
* @param {T[]} array
*/
const shuffle = ([...array]) => {
let currentIndex = array.length
let temporaryValue
let randomIndex
// While there remain elements to shuffle...
while (currentIndex !== 0) {
// Pick a remaining element...
randomIndex = Math.floor(Math.random() * currentIndex)
currentIndex -= 1
// And swap it with the current element.
temporaryValue = array[currentIndex]
array[currentIndex] = array[randomIndex]
array[randomIndex] = temporaryValue
}
return array
}
module.exports = shuffle