-
Notifications
You must be signed in to change notification settings - Fork 0
/
deck.mjs
98 lines (78 loc) · 1.85 KB
/
deck.mjs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
import { Card, Suit, Rank } from './card.mjs';
export function Deck() {
this.cards = new Array();
}
Deck.prototype.fill = function() {
this.clear();
for (let suit of Suit) {
for (let rank of Rank) {
this.add(Card[suit][rank]);
}
}
};
Deck.prototype.shuffle = function(rand = Math.random) {
let index = this.cards.length;
while (index != 0) {
let shuffle = Math.floor(rand() * index--);
let card = this.cards[index];
this.cards[index] = this.cards[shuffle];
this.cards[shuffle] = card;
}
};
Deck.prototype.sort = function(comparator) {
let length = this.cards.length - 1;
do {
var swapped = false;
for (let i = 0; i < length; i++) {
let card = this.cards[i];
let other = this.cards[i + 1];
if (comparator(card, other) > 0) {
this.cards[i] = other;
this.cards[i + 1] = card;
swapped = true;
}
}
} while (swapped);
};
Deck.prototype.add = function(card) {
this.cards.push(card);
};
Deck.prototype.addAll = function(cards) {
for (let card of cards) {
this.add(card);
}
};
Deck.prototype.draw = function(count = 4) {
return this.cards.splice(0, count);
};
Deck.prototype.remove = function(card) {
let index = this.cards.indexOf(card);
if (index != -1) {
this.cards.splice(index, 1);
}
};
Deck.prototype.removeAll = function(cards) {
for (let card of cards) {
this.remove(card);
}
};
Deck.prototype.contains = function(card) {
return this.cards.includes(card);
};
Deck.prototype.size = function() {
return this.cards.length;
};
Deck.prototype.empty = function() {
return this.cards.length <= 0;
};
Deck.prototype.clear = function() {
while (this.cards.length) {
this.cards.pop();
}
};
Deck.prototype[Symbol.iterator] = function*() {
let iterator = this.cards.values();
for (let card of iterator) {
yield card;
}
};