Using a previous question as a base point, asked here. I am trying to create a full Blackjack game and running into an issue with creating a Hand object that holds key:value pairs for {name: cards[]: total: status:}.
I am trying to add together the numbers in the cards[] array dynamically using the reduce() method but running into issues. Since the cards haven't been dealt yet, I get the error: Reduce of empty array with no initial value at Array.reduce().
Here is the code I have:
function DrawOne() {
let card = cardsInDeck.pop();
return card;
}
function Hand(name, cards, total, status) {
this.name = name;
this.cards = [];
this.total = total;
this.status = status;
}
var playerHands = new Array();
function InitialDealOut() {
++handNumber;
let newHand = 'playerHand0' + handNumber;
let handCards = [];
let handTotal = handCards.reduce(function(sum, value) {
return sum + value;
});
let playerHand = new Hand (newHand, handCards, handTotal, 'action');
p1 = DrawOne();
handCards.push(p1.value);
p2 = DrawOne();
handCards.push(p2.value);
}
InitialDealOut();
If I place the reduce() method at the end of the function, it returns a "handTotal is not defined" error.
Is there a way of either delaying the reduce() method to run after or a more efficient way of adding the numbers in the array together as more cards are drawn? I hope this makes sense, if there is more clarification needed please let me know.
Any insights would be appreciated.