Monday, February 16, 2009

Cards, Closures, and Code, Oh My!

the French suits
  1. Create a Card(suit, number) constructor with data members suit and number. Make it so that it is impossible to change the suit and number of a card (yes, you will need to use closures). Create the following functions for this prototype:
    1. toString(): returns a string representation of the card, for example: AD, 4C, 2D.
    2. equal(otherCard): returns true if this card equals otherCard.
    3. cmp(otherCard): returns -1 if the number of this card is less than otherCard, 1 if it is greater, and 0 if they are the same.
  2. Create Deck constructor with data members cards which is initially an empty array. It should also have the following member functions:
    1. shuffle: shuffles the cards. Extra credit: what is the minimum number of swaps required to ensure that a deck is shuffled?
    2. addCards(x): takes as input x which can either be an array of Cards, or a Deck, or just a Card, and adds it to the deck.
    3. deal(): returns a card from the top of the deck and removes it from the deck.

2 comments:

  1. How do we distinguish between a Deck and a Card. typeof returns object for both.

    Right now this is how I'm going about this:
    function Card(suit, num) {
    this.getClass = function () {return "card"; }; and the same for deck

    then simply calling objectName.getClass()

    wrong?

    ReplyDelete
  2. You can check which constructor created an object.

    d.constructor == Card

    or

    d.constructor == Deck

    ReplyDelete