This repository has been archived by the owner on Apr 24, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
queue.js
89 lines (78 loc) · 2.2 KB
/
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
"use strict";
(function() {
var
Queue = function() {
};
Queue.prototype = {
index: 0,
length: 0,
add: function(callback) {
this.push(new Entry(this, callback));
return this;
},
put: function(callback) {
this.splice(this.index+1, 0, new Entry(this, callback));
return this;
},
run: function(index) {
if(!index ) {
index = this.index;
}
var entry;
if( entry = this[index] ) {
this.index = index;
if( entry.callback.apply(entry, [entry]) === true ) {
entry.next();
return true;
}
}
return false;
},
wait: function(ms) {
//TODO Can not be used inside of entry callback
return this.add(function() {
window.setTimeout(this.next.bind(this), ms);
});
},
skip: function(steps) {
//TODO Can not be used inside of entry callback
return this.add(function() {
this.next(steps);
});
},
reset: function() {
this.index = 0;
return this;
},
toArray: function() {
var i, cbArray = [];
for(i in this) {
if( this.hasOwnProperty(i) ) {
cbArray.push(this[i].callback);
}
}
return cbArray;
},
//Behaves like an Array's method
push: [].push, sort: [].sort, splice: [].splice
};
var
Entry = function(queue, callback) {
this.queue = queue;
this.callback = callback;
};
Entry.prototype = {
next: function(steps) {
return this.queue.run(this.queue.index+(steps||1));
},
prev: function(steps) {
return this.next(-steps);
}
};
if(typeof define === "function" && define.amd)
define(function() { return Queue; });
else if(typeof module === "object" && module.exports)
module.exports = Queue;
else
window.Queue = Queue;
})();