ts-cards
Version:
Cards but in typescript
68 lines (67 loc) • 2.1 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.Deck = void 0;
var Deck = /** @class */ (function () {
function Deck(cards) {
if (cards === void 0) { cards = []; }
this.cards = [];
this.drawPile = [];
for (var _i = 0, cards_1 = cards; _i < cards_1.length; _i++) {
var card = cards_1[_i];
this.cards.push(card);
}
}
Object.defineProperty(Deck.prototype, "totalLength", {
get: function () {
return this.cards.length;
},
enumerable: false,
configurable: true
});
Object.defineProperty(Deck.prototype, "remainingLength", {
get: function () {
return this.drawPile.length;
},
enumerable: false,
configurable: true
});
Deck.prototype.shuffleDrawPile = function () {
shuffle(this.drawPile);
};
// shuffles the whole deck and creates the draw pile
Deck.prototype.shuffle = function () {
var _a;
this.drawPile.length = 0;
(_a = this.drawPile).push.apply(_a, this.cards);
this.shuffleDrawPile();
};
Deck.prototype.draw = function (count) {
if (count === void 0) { count = 1; }
if (!this.drawPile.length) {
throw new Error('Deck: Cannot draw from deck, no cards remaining');
}
if (count < 0) {
return [];
}
var cards = this.drawPile.splice(0, count);
return cards;
};
return Deck;
}());
exports.Deck = Deck;
function shuffle(array) {
var currentIndex = array.length;
var temporaryValue;
var randomIndex;
// While there remain elements to shuffle...
while (0 !== currentIndex) {
// Pick a remaining element...
randomIndex = Math.floor(Math.random() * currentIndex);
currentIndex -= 1;
// And swap it with the current element.
temporaryValue = array[currentIndex];
array[currentIndex] = array[randomIndex];
array[randomIndex] = temporaryValue;
}
return array;
}