-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathstate-stack.js
More file actions
59 lines (49 loc) · 851 Bytes
/
state-stack.js
File metadata and controls
59 lines (49 loc) · 851 Bytes
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
class StateStack {
constructor(options){
if(!options){
options = {};
}
this.maxLength = options.maxLength || 10;
this.history = [];
this.p = -1;
}
get length(){
return this.history.length;
}
get state(){
return this.history[this.p];
}
pushState(state){
this.history = this.history.splice(0, this.p + 1);
this.history.push(state);
this.p++;
return this.state;
}
back(){
if(this.p > -1) {
this.p--;
}
return this.state;
}
forward(){
if(this.p < this.length - 1){
this.p++;
}
return this.state;
}
go(num){
let step = Number(num);
if(isNaN(step)){
return this.state;
}
let tempPosition = this.p + step;
if(tempPosition > this.length){
this.p = this.length - 1;
}else if(tempPosition < 0){
this.p = -1;
}else {
this.p = tempPosition;
}
return this.state;
}
}