Useful JavaScript Game Extensions: Array#shuffle

Do the shuffle! Array#shuffle

Part 7/256

Shuffling is important, especially in card games.

/**
 * Returns a new array with the elements all shuffled up.
 *
 * @returns A new array that is randomly shuffled.
 * @type Array
 */
Array.prototype.shuffle = function() {
  var shuffledArray = [];

  this.each(function(element) {
    shuffledArray.splice(rand(shuffledArray.length + 1), 0, element);
  });

  return shuffledArray;
};

Notice how building on the previous components of rand and each makes this method much easier to write. You’ll find that when you surround yourself with great APIs things constantly become easier and easier, whereas when you are surrounded with terrible APIs things become harder and harder.

Author: Daniel X

Heretic priest of the Machine God. I enjoy crawling around in Jeff Bezo's spaceship, bringing technology to the people, and long walks outside of time and space.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: