/
index.js
99 lines (83 loc) · 1.4 KB
/
index.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
94
95
96
97
98
99
/**
* Expose `History`.
*/
module.exports = History;
/**
* Initialize a `History` with the given `vals`.
*
* @param {Array} vals
* @api public
*/
function History(vals) {
this.vals = vals || [];
this.reset();
this.max(1000);
}
/**
* Cap the entries.
*
* @api private
*/
History.prototype.cap = function(){
var max = this._max;
var len = this.vals.length;
var remove = len - max;
if (remove <= 0) return;
while (remove--) this.vals.shift();
this.reset();
};
/**
* Set the maximum number of entries to `n`.
*
* @param {Number} n
* @return {History}
* @api public
*/
History.prototype.max = function(n){
this._max = n;
this.cap();
return this;
};
/**
* Add a `val`.
*
* @param {Object} val
* @return {History}
* @api public
*/
History.prototype.add = function(val){
this.i = this.vals.push(val);
this.cap();
return this;
};
/**
* Cycle backwards through history.
*
* @return {Object}
* @api public
*/
History.prototype.prev = function(){
if (this.i <= 0) return;
return this.vals[--this.i];
};
/**
* Cycle forward through history.
*
* @return {Object}
* @api public
*/
History.prototype.next = function(){
var len = this.vals.length;
if (this.i >= len) return;
return this.vals[++this.i];
};
/**
* Reset the history index.
*
* @return {History}
* @api public
*/
History.prototype.reset = function(){
this.i = this.vals.length;
return this;
};