Skip to content

Instantly share code, notes, and snippets.

@KooiInc
Created May 18, 2023 16:09
Show Gist options
  • Save KooiInc/631f9e8a16740dcfc3a609443edca18f to your computer and use it in GitHub Desktop.
Save KooiInc/631f9e8a16740dcfc3a609443edca18f to your computer and use it in GitHub Desktop.
Shuffle Array randomly (Fisher-Yates, use crypto)
function shuffle(array) {
const someNr = (min = 0, max = Number.MAX_SAFE_INTEGER) =>
Math.floor( ( [...crypto.getRandomValues( new Uint32Array(1))][0] / 2**32 ) *
(max - min + 1) + min );
const swap = (i1, i2) => [array[i1], array[i2]] = [array[i2], array[i1]];
return (Array(array.length).fill(0).forEach( (_, i) => swap( i, someNr(0, i) ) ), array);
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment