Skip to content

Instantly share code, notes, and snippets.

Created May 14, 2013 19:31
Show Gist options
  • Save anonymous/5578763 to your computer and use it in GitHub Desktop.
Save anonymous/5578763 to your computer and use it in GitHub Desktop.
Quick script to shuffle a deck of cards. More specifically, to hand back cards from a deck one at a time in random order.
var cltnc = (function() {
return {
CardDeck: function(ary) {
if ("string" == typeof(ary)) {
this.ary = ary.split("");
} else {
this.ary = ary;
}
this.remaining = ary.length;
this.nextCard = function() {
if (this.remaining <= 0) {
throw new RangeError('All the cards have been dealt');
}
// Take a random card out of all
// available, then move this card to the end
var idx = Math.floor(Math.random() * this.remaining);
var ret = this.ary[idx];
this.ary[idx] = this.ary[this.remaining - 1];
this.ary[this.remaining - 1] = ret;
this.remaining--;
return ret;
};
}
};
}());
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment