Skip to content

Instantly share code, notes, and snippets.

@thatrubylove
Last active September 13, 2015 19:33
Show Gist options
  • Save thatrubylove/437d7d2071cb55fafbfe to your computer and use it in GitHub Desktop.
Save thatrubylove/437d7d2071cb55fafbfe to your computer and use it in GitHub Desktop.
<script src="flat_map.js"></script>
<script src="shuffle.js"></script>
<script src="card.js"></script>
<script src="deck.js"></script>
var Card = function(rank, suit) {
var self = this;
self.rank = rank;
self.suit = suit;
var toString = function() {
return self.rank + " of " + self.suit;
}
return {
name: toString(),
suit: suit,
rank: rank
}
};
var Deck = function() {
var self = this;
var cards = [];
var SUITS = ['Diamonds', 'Clubs', 'Hearts', 'Spades'];
var RANKS = ['Ace', 'Two', 'Three', 'Four', 'Five',
'Six', 'Seven', 'Eight', 'Nine',
'Ten', 'Jack', 'Queen', 'King'];
var buildDeck = function() {
var cards = SUITS.flatMap(function(suit, i) {
return RANKS.map(function(rank, i) {
return new Card(rank, suit);
});
});
return cards.shuffle();
}
return {
cards: buildDeck(),
}
};
// I want a flat map!
Array.prototype.flatMap = function(f) {
return Array.prototype.concat.apply([], this.map(f));
}
// Fischer/Yates
Array.prototype.shuffle = function() {
var self = this;
var m = self.length, t, i;
while (m) {
i = Math.floor(Math.random() * m--);
t = self[m];
self[m] = self[i];
self[i] = t;
}
return self;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment