Last active
December 9, 2025 09:28
-
-
Save goofballLogic/1ad1fd00d15579fa5624b01d90c950a9 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| // below here we can use functional structures again | |
| const suits = ["♠", "♥", "♣", "♦"]; | |
| const cards = ["A", "K", "Q", "J", "9", "8", "7", "6", "5", "4", "3", "2"]; | |
| function new_deck() { | |
| return suits.flatMap(suit => | |
| cards.map(card => `${card}${suit}`)); | |
| } | |
| function shuffle(cards, iterations = 1000) { | |
| if(iterations < 1) return cards; | |
| const i = Math.floor(Math.random() * cards.length); | |
| const sorted = [...cards]; | |
| const [extracted] = sorted.splice(i, 1); | |
| return shuffle( | |
| [...sorted, extracted], | |
| iterations - 1 | |
| ); | |
| } | |
| function draw(deck, n) { | |
| return deck.splice(0, n); | |
| } | |
| // problem is defined specifying classes and methods so we are forced to use one for the entry point | |
| class Deck { | |
| #deck; | |
| constructor() { this.#deck = new_deck(); } | |
| shuffle() { this.#deck = shuffle(this.#deck); } | |
| draw(n) { return draw(this.#deck, n); } | |
| } | |
| // demo | |
| const deck = new Deck(); | |
| deck.shuffle(); | |
| console.log(deck.draw(5)); | |
| console.log(deck.draw(5)); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment