liveBook · Manning

Card

As explained in Get Programming with JavaScript Next: New features of ECMAScript 2015, 2016, and beyond

An individual playing card with suit and face attributes in a card deck.

How do you turn a playing card into something a program can store and use? Represent each card as a simple object with a suit and a face. section 26.1

A card supports several practical operations:

  • Use Sets for the available suits and faces, and a Map for face values; treat aces separately because their value can be 1 or 11. section 26.1
  • Track whether each card is face up or face down by mapping the card object to a Boolean. section 26.1
  • Build a 52-card deck from every suit-and-face combination, then shuffle it before use. section 26.1
  • Pop cards from the deck, mark them face up, deal initial hands, and count hands while adjusting aces. section 26.1

Creating a deck

Create each card as { face, suit }, add it to a Set, and shuffle by temporarily converting the Set to an Array. The array provides indexes for swapping; the shuffled values then refill the Set. section 26.1

Listing 26.5. src/cards.js
export function createDeck() { const deck = new Set(); for (const suit of suits) { for (const face of faces) { deck.add({ face, suit }); } } shuffle(deck); return deck; }

Inspect the compact implementation that combines suits and faces into card objects and returns a shuffled deck. section 26.1

How Get Programming with JavaScript Next: New features of ECMAScript 2015, 2016, and beyond covers it

How deep it goes
Explains card creation, shuffling, flipping, dealing, and ace-aware counting through concrete JavaScript implementations.
Examples
Uses a 52-card deck, face-value mappings, flip-state tracking, initial hands, and ace-sensitive hand counts.
What you can do after
Build card objects, generate and shuffle a deck, deal cards, track visibility, and calculate Blackjack hand values.
How it connects
Connects card objects with suits, faces, decks, hands, Set, Map, shuffling, and Blackjack scoring.

Also explained in

Compare how 4 books explain card →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Get Programming with JavaScript Next: New features of ECMAScript 2015, 2016, and beyond. The section links point to the parts of the book it draws on.