forked from cncjs/cncjs
-
Notifications
You must be signed in to change notification settings - Fork 0
/
command-queue.js
93 lines (75 loc) · 2.1 KB
/
command-queue.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
var CommandQueue = function(options) {
var Wrapper = function() {
this._queue = [];
this._executed = 0;
this._loop = false;
this._stopped = true;
this._callbacks = [];
};
Wrapper.prototype.on = function(evt, callback) {
if (evt === 'data' && (typeof callback === 'function')) {
this._callbacks.push(callback);
}
return this;
};
Wrapper.prototype.play = function(options) {
options = options || {};
this._stopped = false;
this._loop = !!options.loop;
this.next();
return this;
};
Wrapper.prototype.pause = function() {
this._stopped = true;
return this;
};
Wrapper.prototype.stop = function() {
this._stopped = true;
this._loop = false;
this._executed = 0;
return this;
};
Wrapper.prototype.replay = function(options) {
this.stop();
this.play(options);
return this;
};
Wrapper.prototype.clear = function() {
this._queue = [];
this._executed = 0;
return this;
};
Wrapper.prototype.push = function(data) {
this._queue = this._queue.concat(data);
return this;
};
Wrapper.prototype.next = function() {
if (this._stopped) {
return this;
}
if (this._loop && this._queue.length > 0 && this._executed >= this._queue.length) {
this._executed = 0;
this.next();
return this;
}
if (this._executed < this._queue.length) {
var data = this._queue[this._executed];
this._executed++;
this._callbacks.forEach(function(callback) {
callback(data);
});
}
return this;
};
Wrapper.prototype.isRunning = function() {
return ! this._stopped;
};
Wrapper.prototype.executed = function() {
return this._executed;
};
Wrapper.prototype.size = function() {
return this._queue.length;
};
return new Wrapper();
};
module.exports = CommandQueue;