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.