On my previous post, someone asked why we use constructor functions. In a nutshell, we use constructors to save us time. In today’s tutorial, I’m going to illustrate this by creating a deck of cards.

In a standard deck of playing cards, each card has a rank (ace through king) and a suit (diamonds, clubs, hearts, or spades). These are the properties of the card. Therefore, our constructor function looks like this:

function Card(r,s){ this.rank = r this.suit = s this.cardName = r + " of " + s; }

Next, we’ll create an array for the suits, and a string (for the sake of brevity) to represent the ranks. We also create a blank array the expected length of our deck, which in this sace is merely the total number of possible cards.

suits = ["diamonds", "clubs", "hearts", "spades"] ranks = "A23456789TJQK" deck = new Array(ranks.length * suits.length);

Now, all we have to do is use two nested loops to get every possible permutation of card to get a full deck. Note that the index for the card’s position in the deck is equivalent to j + i * ranks.length .

for (i = 0; i < suits.length; i++){ for (j = 0; j < ranks.length; j++) deck[j + i * ranks.length] = new Card(ranks[j],suits[i]); }

Now, we have an array of (in this case) 52 strings, all of which have a rank, suit, and name as properties. If we were programming a game, we might add a “value” property, or we could calculate the value in a separate function.

The above result for deck might represent a completely new, unopened pack of cards that you buy from your local grocery store checkout line. Of course, if you want to use it, you’ll need to shuffle the deck before playing. To do this, you use the Fisher-Yates algorithm. Mike Bostock has created a good visualization of this algorithm (as well as the code, and a good explanation of why you should use the particular algorithm). In fairness to Mr. Bostock, I won’t copy and paste his code here, so you’ll have to go there and read his excellent article yourself.

Anyhow, after this is done, you should have a fully shuffled deck of cards, ready to play your favorite game. Now, all you’ve got to do is deal. Fortunately, JavaScript makes this easy for us with the shift method. Essentially, shift removes the first item of the array, do we just need to do this for the number of cards we want in a hand. In other words, we put the following into a loop:

function stackDeal() { if (this.cards.length < 0) return this.cards.shift(); else return null; }

You can see the code demonstrated here. To shuffle the deck, press the “shuffle” button. To deal a hand, press “deal”, which moves the top five cards from the shuffled deck to your hand. If you run out of cards, the deck will automatically be re-shuffled.

You can also change the type of deck by changing the value of suits and ranks . For instance, to generate a “Spanish” deck, you would use suits=['bastos', 'oros', 'copas', 'espadas'] .

How can ace be one and eleven? What kind of God would allow that?!