-
Notifications
You must be signed in to change notification settings - Fork 0
/
deck.js
82 lines (67 loc) · 1.71 KB
/
deck.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
import map from 'lodash/map'
import times from 'lodash/times'
const SUITS = ['Club', 'Diamond', 'Heart', 'Spade']
const RANKS = ['Ace', 'Two', 'Three', 'Four', 'Five', 'Six', 'Seven', 'Eight', 'Nine', 'Ten', 'Jack', 'Queen', 'King']
const RANKS_SHORT = ['A', '2', '3', '4', '5', '6', '6', '8', '9', '10', 'J', 'Q', 'K']
export const NUMBER_OF_CARDS = 52
/**
* Playing card with suite and rank
* @class Card
*/
export class Card {
constructor(i) {
this.index = i
this.suit = SUITS[i % 4]
this.rank = RANKS[i % 13]
}
toString() {
return `${this.suit} ${this.rank}`
}
}
/**
* Deck of playing cards
* @class Deck
*/
export class Deck {
constructor() {
this._cards = []
this._populate()
this.shuffle()
}
_populate() {
// creates array of indexes from 0 to 51:
let indexArray = Array.from(Array(NUMBER_OF_CARDS).keys())
this._cards = map(indexArray, (i) => new Card(i))
}
hasCards() {
return this._cards.length > 0
}
get cardsLeft() {
return this._cards.length;
}
/**
- returns no value
- makes cards in the deck being randomly permuted
*/
shuffle() {
let n = this._cards.length
if (n === 0) {
return false;
}
// pseudo-random number generator
times(n, (i) => {
let r = Math.floor( Math.random() * n )
let temp = this._cards[i]
this._cards[i] = this._cards[r]
this._cards[r] = temp
})
}
/**
- returns one card from the deck to the caller
- 52 calls to dealOneCard() should result in caller being provided all 52 cards of the deck in random order
- when caller makes 53rd call to dealOneCard(), no card is dealt
*/
dealOneCard() {
return this.hasCards() ? this._cards.pop() : null;
}
}