-
Notifications
You must be signed in to change notification settings - Fork 0
/
loop-iterator.js
75 lines (62 loc) · 1.97 KB
/
loop-iterator.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
;(function(glob) {
function LoopIterator(array, history) {
if (!(this instanceof LoopIterator)) { return new LoopIterator(array, history); }
this._currentIndex = 0
this._array = array
if (typeof history === 'number' && history > 0){
this._history = new Array(history);
}
}
var p = LoopIterator.prototype;
p.updateHistory = function(){
var t = this;
if (t._history){
t._history.shift();
t._history.push({element:t.current(), index:t._currentIndex});
}
}
p.nextIndex = function(){
var t = this;
return t.currentIndex(t._currentIndex+1);
}
p.prevIndex = function(){
var t = this;
return t.currentIndex(t._currentIndex-1);
}
p.currentIndex = function(index){
var t = this;
if (index !== undefined && index != t._currentIndex) {
t.updateHistory();
var len = t._array.length;
//circulate
index = index < 0 ? len+index: (index>=len ? index%len:index);
t._currentIndex = index;
}
return t._currentIndex;
}
p.next = function(){ return this._array[this.nextIndex()]; }
p.prev = function(){ return this._array[this.prevIndex()]; }
p.current = function(){ return this._array[this._currentIndex]; }
p.history = function(level, returnIndex){
var t = this;
if (!t._history) return null;
var maxLevel = t._history.length;
if (level === undefined) level = 1;
if (level === 0) return (returnIndex ? t._currentIndex : t.current());
if (level > maxLevel) return undefined;
var historyElement = t._history[maxLevel - level];
if (!historyElement) return null;
return (returnIndex ? historyElement.index : historyElement.element);
}
p.historyIndex = function(level){
return this.history(level, true)
}
// Export for node and browserify
if (typeof module !== 'undefined' && module.exports) {
module.exports = LoopIterator;
}
// Export for usage in script tags
else {
glob.LoopIterator = LoopIterator;
}
})(this);