forked from cgolden15/tetris
-
Notifications
You must be signed in to change notification settings - Fork 3
/
RandomBag.js
49 lines (41 loc) · 1.16 KB
/
RandomBag.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
function RandomBag(queueSize) {
// start off empty
this.available = [];
this.queue = [];
// initialize by refilling the queue
while (this.queue.length < queueSize) {
this.queue.push(this.nextAvailable());
}
}
RandomBag.initialList = ['i', 'o', 'j', 'l', 'z', 's', 't'];
/**
* Returns the letters of the queue
* @returns {[Char]} the letters of the queue in order of oldest to newest
*/
RandomBag.prototype.getQueue = function () {
return this.queue;
};
/**
* Moves the queue forward by one
* @returns {Char} the poped value
*/
RandomBag.prototype.popQueue = function () {
var res = this.queue.shift();
this.queue.push(this.nextAvailable());
return res;
};
/**
* gets the next letter for the queue, and updates the random bag state
* @returns {Char} the next letter for the queue
* @private
*/
RandomBag.prototype.nextAvailable = function() {
var index, res;
// if the available needs to be rebuilt
if (this.available.length === 0) {
this.available = RandomBag.initialList.slice(0); // shallow copy
}
index = Math.floor(Math.random()*this.available.length);
res = this.available.splice(index, 1)[0];
return res;
};