A co-worker of mine sent me some advice on the JavaScript deck of cards I set up a while back. Everything he said was spot on. Jim, if you’re out there, you’re insight and advice is always welcome and highly respected. Thanks!
Read your blog. 🙂
In the interest of academic feedback (don’t take any of this in a negative way), I have a few comments.
It’s hard to tell from the current function names, but if the “same_suit” and “same_type” Card methods are meant to be “is_same_…” functions, they you need to change the “=” to “==”.
Card = Class.create({ initialize: function(type,suit) { this.type = type; this.suit = suit; }, same_suit: function(suit) { return this.suit == suit; }, same_type: function(type) { return this.type == type; }, toString: function(){ return this.type + ' of ' + this.suit; } });
JS supports the ‘+=’ operator for strings, so you could change the “message = message + …” to “message += …” in the Deck::toString method.
The first time through the Deck::toString function, the modulo check will be true, resulting in message beginning with a ‘n’ character. Wasn’t sure if that is what you wanted.
Here’s a minor optimization for the Deck::toString function. It removes the modulo operation from the loop, which is performed 52 times on a full deck, and handles the all of the leading/trailing whitespace (tabs and newlines) automatically:
toString: function() { var message = ''; var i = 0, n = this.cards.length - 2; for(; i < n; ) { message += this.cards[i++] + 'tt' + this.cards[i++] + 'n'; } if (i < this.cards.length) { message += this.cards[i++]; } if (i < this.cards.length) { message += 'tt' + this.cards[i]; } return message; }
The following code:
var face_cards = "King,Queen,Jack" face_cards = face_cards.split(',');Could be:
var face_cards = ["King","Queen","Jack"];
I don't think you need the "var i" in the Deck::add_card method.
PS: One other minor update, I got started thinking about UNO and decided to break out the French or Anglo American deck specifications out to a separate class and file.
PPS: Jim caught me using a "=" in place of a "==". These were methods that I hadn't tried yet, but knew that I would need in the future. This is exactly the sort of thing that would have been instantly caught had I written out some tests. I'm a bit late to the game on TDD, but it's something I've been toying with in Ruby and I'm starting to come around. I don't even know where to start unit testing in JavaScript, but I plan on doing a bit of homework on the matter so stay tuned!
Download the code!
JavaScript Deck of Cards V2
Current Version