JSFiddle - React, Tailwind, and code Playground
by TheCrossCarrier
JavaScript
class Deck {
constructor(quantity = 52) {
/**
* Number of cards in the deck.
*
* @var int
*/
this.quantity = quantity
/**
* A card deck suits.
*
* @var array
*/
this.suits = ['heart', 'diamond', 'club', 'spade']
/**
* A card deck values.
*
* @var array
*/
this.values = ['A', 'K', 'Q', 'J', '10', '9', '8', '7', '6']
if (this.quantity == 52) this.values.push(...['5', '4', '3', '2'])
/**
* A card deck.
*
* @var array
*/
this.deck = []
this.generateDeck()
this.shuffle()
console.log(this.deck);
}
generateDeck() {
this.deck = this.suits.flatMap(suit =>
this.values.map(value => {
return { value: value, suit: suit }
})
)
}
shuffle() {
for (let i = 0; i < this.quantity; i++) {
var newIndex = Math.floor(Math.random() * this.quantity)
[this.deck[i], this.deck[newIndex]] = [this.deck[newIndex], this.deck[i]]
}
}
}
const deck = new Deck()