I tried the following commands using create function keywords to split up the logic and got a simple way to handle 3 events at once.
/* create a function to create a deck of poker cards. create a function to deal 5 cards from the deck. create a function to get the value of hands dealt. */
var deck = [];
var suits = ['spades', 'hearts', 'diamonds', 'clubs'];
var values = ['ace', '2', '3', '4', '5', '6', '7', '8', '9', '10', 'jack', 'queen', 'king'];
function createDeck() {
for (var suit of suits) {
for (var value of values) {
deck.push(value + ' of ' + suit);
}
}
}
function dealCards() {
var hand = [];
for (var i = 0; i < 5; i++) {
hand.push(deck.pop());
}
return hand;
}
function getHandValue(hand) {
var value = 0;
for (var card of hand) {
var cardValue = card.split(' ')[0];
if (cardValue === 'ace') {
value += 11;
} else if (cardValue === 'jack' || cardValue === 'queen' || cardValue === 'king') {
value += 10;
} else {
value += parseInt(cardValue);
}
}
return value;
}
The value of a hand in poker is not determined solely by individual card values, but even so it’s a step in the right direction. After that It was a simple matter to call those functions and log the results…
/* call createDeck */
createDeck();
/* console.log(getHandValue(dealCards)); */
console.log(getHandValue(dealCards()));