I'm currently building a blackjack game, and one of my classes is called "Deck". This deck needs to do two things:
- Return a set of cards that other objects can use (this is equivalent to dealing those cards out)
- Remove those cards from the deck (once a card has been dealt, it should be removed).
At the moment, I've implemented these two pieces of functionality by creating two methods: selectCards()
and removeIndexFromDeck
. I first call selectCards()
which returns the selected cards, but also calls removeIndexFromDeck()
.
Does this approach violate best practices? It looks like my selectCards()
function has both a return value and side-effects.
If it does violate best practices, how would I change these methods, but make sure I'm still able to return the selected cards and also remove them from the deck.
Thanks!
class Deck {
constructor() {
this.deck = [];
['♦', '♣', '♥', '♠'].forEach(suit => {
['A', '2', '3', '4', '5', '6', '7', '8', '9', '10', 'J', 'Q', 'K'].forEach(value => {
this.deck.push(`${value}${suit}`);
});
});
}
selectCards(numCards) {
let selectedCards = [];
while (numCards > 0) {
let randIndex = Math.floor(Math.random() * this.deck.length);
selectedCards.push(this.deck[randIndex]);
this.removeIndexFromDeck(randIndex);
numCards -= 1;
}
return selectedCards;
}
removeIndexFromDeck(index) {
this.deck.splice(index, 1);
}
}