'use strict';
function Deck(cards) {
this.cards = cards;
this.registerCards();
}
Deck.prototype.deckHasCards = function() {
if (!this.cards || this.cards.constructor.name !== 'Array' || this.cards.length === null) {
throw new Error('there are no cards in the deck');
}
};
Deck.prototype.registerCards = function() {
this.deckHasCards();
this.cards = this.cards.map(function(card) {
return card.setDeck(this);
}.bind(this));
};
Deck.prototype.shuffle = function() {
this.deckHasCards();
var currentIndex = this.cards.length, temporaryValue, randomIndex;
while (0 !== currentIndex) {
randomIndex = Math.floor(Math.random() * currentIndex);
currentIndex -= 1;
temporaryValue = this.cards[currentIndex];
this.cards[currentIndex] = this.cards[randomIndex];
this.cards[randomIndex] = temporaryValue;
}
};
Deck.prototype.cardBelongsToDeck = function(card) {
return card.getDeck() === this;
}
Deck.prototype.getNextCard = function () {
this.deckHasCards();
return this.cards.shift();
};
function Card(value) {
this.name = value;
this.deck = null;
}
Card.prototype.setDeck = function(deck) {
this.deck = deck;
return this;
};
Card.prototype.getDeck = function() {
return this.deck;
};
var possibleCardSet = ['Ace', '2', '3', '4'];
var cards = possibleCardSet.map(function (name) {
return new Card(name);
});
/*
var deck = new Deck(cards);
deck.shuffle();
var nextCard = deck.getNextCard();
console.log(nextCard);
*/
var card = {
name: null,
deck: null,
setDeck: function(deck) {
this.deck = deck;
return this;
},
getDeck: function() {
return this.deck;
}
};
var deck = {
cards: [],
deckHasCards: function() {
if (!this.cards || this.cards.constructor.name !== 'Array' || this.cards.length === null) {
throw new Error('there are no cards in the deck');
}
},
registerCards: function(cards) {
this.cards = cards.map(function(card) {
return card.setDeck(this);
}.bind(this));
},
shuffle: function() {
this.deckHasCards();
var currentIndex = this.cards.length, temporaryValue, randomIndex;
while (0 !== currentIndex) {
randomIndex = Math.floor(Math.random() * currentIndex);
currentIndex -= 1;
temporaryValue = this.cards[currentIndex];
this.cards[currentIndex] = this.cards[randomIndex];
this.cards[randomIndex] = temporaryValue;
}
},
cardBelongsToDeck: function(card) {
return card.getDeck() === this;
},
getNextCard: function () {
this.deckHasCards();
return this.cards.shift();
}
};
since you wrote it in ES3 and this would be some implementations
I was lazy so the shuffle is from