-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
127 lines (107 loc) · 2.93 KB
/
index.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
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
'use strict';
/*
* Card = [Suit, Name, Value]
*
* NOTE: Aces in card games are sometimes special in that the value
* can be 1 or 11 (e.g. blackjack) or hi/low (e.g poker). That has
* to be handled at the application level.
*/
const suits = [
'SPADES',
'HEARTS',
'DIAMONDS',
'CLUBS',
];
// Name, point value, poker value
const cards = [
['Ace', 1, 14],
['Two', 2, 2],
['Three', 3, 3],
['Four', 4, 4],
['Five', 5, 5],
['Six', 6, 6],
['Seven', 7, 7],
['Eight', 8, 8],
['Nine', 9, 9],
['Ten', 10, 10],
['Jack', 10, 11],
['Queen', 10, 12],
['King', 10, 13],
];
class Card {
constructor(suit, name, value, pokerValue) {
this.suit = suit;
this.name = name;
let cardTemplate = cards.filter(card => card[0] === name);
if (cardTemplate.length === 1) {
this.value = (value ? value : cardTemplate[0][1]);
this.pokerValue = (pokerValue ? pokerValue : cardTemplate[0][2]);
}
else {
throw "Needs to be a single card type template: " + name;
}
}
isSameAs(cardToCheck) {
return (this.suit === cardToCheck.suit)
&& (this.name === cardToCheck.name)
&& (this.value === cardToCheck.value);
}
isSameSuit(cardToCheck) {
return this.suit === cardToCheck.suit;
}
isSameName(cardToCheck) {
return this.name === cardToCheck.name;
}
}
class Deck {
constructor(allCards = null) {
this.cardIndex = 0;
if (allCards) {
this.allCards = allCards;
}
else {
this.allCards = [];
for (let i = 0; i < suits.length; i++) {
for (let j = 0; j < cards.length; j++) {
this.allCards.push(new Card(suits[i], cards[j][0], cards[j][1], cards[j][2]));
}
}
}
}
shuffle() {
this.cardIndex = 0;
let currentIndex = this.allCards.length,
temporaryValue,
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 = this.allCards[currentIndex];
this.allCards[currentIndex] = this.allCards[randomIndex];
this.allCards[randomIndex] = temporaryValue;
}
return this.allCards;
}
nextCard() {
if (this.cardIndex >= this.allCards.length) {
return false;
}
let card = this.allCards[this.cardIndex];
this.cardIndex++;
return card;
}
}
let createDeck = () => {
let deck = new Deck();
return deck;
}
module.exports = {
suits: suits,
cardTypes: cards,
createDeck: createDeck,
Card: Card,
Deck: Deck
}