Skip to content

Instantly share code, notes, and snippets.

@joshwashywash
Last active March 6, 2023 16:45
Show Gist options
  • Save joshwashywash/98303ea29775feb052b1c722adf921d0 to your computer and use it in GitHub Desktop.
Save joshwashywash/98303ea29775feb052b1c722adf921d0 to your computer and use it in GitHub Desktop.
shuffles an array in place
const swap = <T>(t: T[], i: number, j: number) => {
[t[i], t[j]] = [t[j], t[i]];
};
export const shuffle = <T>(t: T[]) => {
for (let i = t.length - 1; i > 0; i -= 1) {
const j = Math.floor(Math.random() * (i + 1));
swap(t, i, j);
}
};
import { shuffle } from 'shuffle';
const pokemon = [
'squirtle',
'snorlax',
'haunter',
'mankey',
'mewtwo',
];
shuffle(pokemon);
console.log(pokemon); // some new arrangement
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment