liveBook · Manning

Shuffle

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

An operation that rearranges a collection into a random order.

Shuffling rearranges a collection into a random order. For a card deck stored as a Set, first copy its values into an array because Sets have insertion order but no indexes. section 26.1

The shuffle operation proceeds in a short sequence:

  • Spread the Set into an array. section 26.1
  • Visit each array index and choose a random swap index with Math.random(). section 26.1
  • Swap the cards, clear the original Set, and add the cards back in their new order. section 26.1

Shuffling a blackjack deck

createDeck builds a Set from every suit-and-face combination, calls shuffle(deck), and returns the rearranged deck ready for dealing. section 26.1

Listing 26.6. src/cards.js
export function shuffle(deck) { const cards = [ ...deck ]; 1 let idx = cards.length; while (idx > 0) { idx-- 2 const swap = Math.floor(Math.random() * cards.length); 3 const card = cards[swap]; 4 cards[swap] = cards[idx]; 5 cards[idx] = card; 6 } deck.clear(); 7 cards.forEach(card => deck.add(card)); 8 }

Inspect the shuffle implementation, including the loop, random swap, deck clearing, and reinsertion steps. section 26.1

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

How deep it goes
Explains Set-to-array conversion, random selection, swapping, clearing, and reinsertion without discussing randomness quality.
Examples
Uses a 52-card Set assembled from suits and faces, then shuffled before cards are dealt.
What it assumes
Assumes familiarity with Set, arrays, spread syntax, loops, and insertion order.
What you can do after
Build it from scratch by swapping array entries and restoring their order in a Set.
How it connects
Connects Set, Array, spread syntax, Math.random(), loops, and card dealing.

Also explained in

Compare how 3 books explain shuffle →

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.