JSFiddle - React, Tailwind, and code Playground

by denniswaltermartinez

JavaScript

function Deck() {
    var cards = ['Ace', 'Two', 'Three', 'Four', 'Five', 'Six', 'Seven', 'Eight', 'Nine', 'Ten', 'Jack', 'Queen', 'King'],
        cardTypes = ['Spades', 'Clubs', 'Diamons', 'Hearts'];

    this.cards = [];

    var i = 0,
        l = cardTypes.length;

    for (; i < l; i++) {
        var x = 0,
            t = cards.length;

        for (; x < t; x++)
        this.cards.push(cards[x] + ' of ' + cardTypes[i]);
    }
};

Deck.prototype.draw = function (limit) {
    var cards = [],
        i = 0;
    
    for (; i < limit; i++) {
        cards[i] = this.cards[i];
        this.cards.splice(i, 1);
    }
    
    return cards;
};

// Fisher Yates shuffle.
Deck.prototype.shuffle = function () {
    var m = this.cards.length,
        t, i;

    // While there remain elements to shuffle…
    while (m) {

        // Pick a remaining element…
        i = Math.floor(Math.random() * m--);

        // And swap it with the current element.
        t = this.cards[m];
        this.cards[m] = this.cards[i];
        this.cards[i] = t;
    }
};

// new deck!
var deck = new Deck();

// shuffle the deck.
deck.shuffle();

// players draw cards. (can also be put into a loop so a player gets cards 1 by 1.)
var player1 = deck.draw(5),
    player2 = deck.draw(5);

// show the player hands.
console.log('player 1 cards:', player1);
console.log('player 2 cards:', player2);