UNPKG

card-games-utils

Version:
73 lines (72 loc) 3.01 kB
"use strict"; var __spreadArray = (this && this.__spreadArray) || function (to, from, pack) { if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) { if (ar || !(i in from)) { if (!ar) ar = Array.prototype.slice.call(from, 0, i); ar[i] = from[i]; } } return to.concat(ar || Array.prototype.slice.call(from)); }; Object.defineProperty(exports, "__esModule", { value: true }); exports.CardDeck = void 0; /** * Class to perform normal operations on any kind of Deck of cards * @class */ var CardDeck = /** @class */ (function () { function CardDeck() { } /** * @method * @static * * shuffle the array of items(cards) * * @template T - generic type of item(card) in the array. * @param {T[]} cards - The array of items(cards) to be shuffled. * @returns {T[]} - A new array with the items(cards) shuffled randomly. */ CardDeck.shuffleCards = function (cards) { var shuffledCards = __spreadArray([], cards, true); shuffledCards.sort(function () { return 0.5 - Math.random(); }); return shuffledCards; }; /** * @method * @static * Distributes specified number of cards per player to given number of players. * * @template T - generic type of item(card) in the array. * @param {T[]} cards - the array of items(cards) to be distributed. * @param {number} numberOfPlayers - the number of players to distribute cards to. * @param {number} cardPerPlayer - the number of cards to be distributed per player. * @param {boolean} shouldDealAround - optional boolean flag, if true, distributes one card per player on each iteration. else distributes all needed cards to player at once and going to another player * @returns {T[][]} - returns 2-dimensional array of cards distributed to each player. * @throws {Error} - if there are not enough cards to distribute among players. */ CardDeck.distributeCards = function (cards, numberOfPlayers, cardPerPlayer, shouldDealAround) { if (shouldDealAround === void 0) { shouldDealAround = true; } if (cards.length < numberOfPlayers * cardPerPlayer) { throw new Error('Not enoughs card to distribute'); } var distributedCardsArr = new Array(numberOfPlayers).fill(null).map(function () { return []; }); if (shouldDealAround) { for (var i = 0; i < cardPerPlayer; i++) { for (var j = 0; j < numberOfPlayers; j++) { distributedCardsArr[j].push(cards.shift()); } } } else { for (var i = 0; i < numberOfPlayers; i++) { for (var j = 0; j < cardPerPlayer; j++) { distributedCardsArr[i].push(cards.shift()); } } } return [distributedCardsArr, cards]; }; return CardDeck; }()); exports.CardDeck = CardDeck;