-
Notifications
You must be signed in to change notification settings - Fork 0
/
CardDeck.js
99 lines (83 loc) · 1.94 KB
/
CardDeck.js
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
98
99
"use strict";
class Card {
constructor(value, rank, suit, identifier) {
this.value = value;
this.rank = rank;
this.suit = suit;
this.identifier = identifier;
this.name = this.rank + " of " + this.suit.name;
}
}
class Deck {
constructor() {
let suits = [
{ name: "Clubs", symbol: "♣" },
{ name: "Diamonds", symbol: "♦" },
{ name: "Hearts", symbol: "♥" },
{ name: "Spades", symbol: "♠" },
];
let ranks = [
"Two",
"Three",
"Four",
"Five",
"Six",
"Seven",
"Eight",
"Nine",
"Ten",
"Jack",
"Queen",
"King",
"Ace",
];
let count = 0;
this.cards = new Map();
suits.forEach((suit) => {
ranks.forEach((rank, value) => {
let identifier = `${value < 9 ? value + 2 : rank[0]}`;
identifier += suit.name[0];
this.cards.set(identifier, new Card(value, rank, suit, identifier));
count++;
});
});
}
/**
* Fisher-Yates Shuffle from Mike Bostock
*/
shuffle(array) {
var m = array.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 = array[m];
array[m] = array[i];
array[i] = t;
}
return array;
}
getDeck(shuffleDeck = true) {
let cardArray = Array.from(this.cards.values()).map( (card) => {return {identifier: card.identifier, value: card.value}});
if(shuffleDeck) {
return this.shuffle(cardArray)
}
return cardArray;
}
getCard(identifier) {
return this.cards.get(identifier);
}
getName(identifier) {
return this.cards.get(identifier).name;
}
getSuit(identifier) {
return this.cards.get(identifier).suit;
}
getRank(identifier) {
return this.cards.get(identifier).rank;
}
}
module.exports = { Card, Deck };