Skip to main content
Post Made Community Wiki by Jesse C. Slicer
Source Link
Jesse C. Slicer
  • 14.2k
  • 1
  • 39
  • 52

I have incorporated most of Marc Rohloff's points (with the notable exception of the last -- I am currently letting Will It Shuffle? work with the result of the IIFE), while minimizing hacking off the linter and have come up with this:

/* eslint-env es6 */
/* eslint no-magic-numbers: ["error", { "ignore": [1] }] */
/* eslint one-var: ["error", "consecutive"] */
(function fisherYates () {

    const shuffle = function shuffle (array) {

        let currentIndex = array.length;

        // While there remain elements to shuffle...
        while (currentIndex) {

            // Pick a remaining element...
            const randomIndex = Math.floor(Math.random() * currentIndex);

            currentIndex -= 1;

            // And swap it with the current element.
            [
                array[currentIndex],
                array[randomIndex]
            ] = [
                array[randomIndex],
                array[currentIndex]
            ];

        }

        return array;

    };

    return shuffle;

}());