How I used JavaScript generators to create a Casino game cards shuffler 🃏

Understand JavaScript generators purpose with a simple example and get your programming skills to next level.

Andréas Hanss
Nov 7, 2019 · 5 min read
Image for post
Image for post

👨🏻‍🔬 What are generator functions ?


Image for post
Image for post

🃏My card shuffler class

What will follow is a simple implementation of a 52 cards classic deck shuffler.

Image for post
Image for post
interface GameCard {
type: ♥️ | ♦️ | ♠️ | ♣️,
value: "1" | "2" | "3" | "4" | "5" | "6" | "7" | "8" | "9" | "J" | "Q" | "K"
}

💻 The entire code of the Card Shuffler in one snippet

  1. Then, initialize the generator iterator by calling getCardDrawer which returns our main tool for this game loop.
  2. Enjoy using generator by asking for new cards, over and over again until the deck get empty.

🎮 The game loop

Once you instantiated the GameShuffler class and the constructor shuffled the entire deck: you can call getCardDrawer method to obtain the iterator that will be used to draw each cards one by one.

const onClick = () => {
const nextCardStatus = cardDrawer1.next();
if (nextCardStatus.done) {
console.log("Deck is now empty!");
} else {
console.log("Picked card is: ", nextCardStatus.value.card);
console.log("Remaining cards in the deck: ", nextCardStatus.value.remainingCards);
}
};
for (const cardStatus of cardDrawer2) {
console.log("Picked card is: ", cardStatus.card);
console.log("Remaining cards in the deck: ", cardStatus.remainingCards);
}

🚛 Takeaway / TLDR; 📦

Generators are nice tools that allows better async functionalities, infinite data streams, lazy evaluated, memory efficient iterations.

JavaScript In Plain English

New JavaScript + Web Development articles every day.

Andréas Hanss

Written by

👨🏻‍💻Javascript’ Tech Lead 🇫🇷 — react | react-native | modern js |🔥 Firebase — https://linktr.ee/scr34mz — Passionated about learning.

JavaScript In Plain English

New JavaScript + Web Development articles every day.

Andréas Hanss

Written by

👨🏻‍💻Javascript’ Tech Lead 🇫🇷 — react | react-native | modern js |🔥 Firebase — https://linktr.ee/scr34mz — Passionated about learning.

JavaScript In Plain English

New JavaScript + Web Development articles every day.

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch

Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore

Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade

Get the Medium app