-
Notifications
You must be signed in to change notification settings - Fork 25
/
Copy pathsessionstore.js
110 lines (86 loc) · 2.28 KB
/
sessionstore.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
100
101
102
103
104
105
106
107
108
109
110
'use strict';
function SessionStore() {
this._sessionLimit = 100;
this._dataKey = 'sessions';
this._sessions = this._getAllSessions();
this._currentSessionIndex = this._sessions.length - 1;
}
/**
* Returns the last execution
* @return {?String}
*/
SessionStore.prototype.getLast = function() {
return this._sessions[this._sessions.length - 1];
};
/**
* @param {String} code
*/
SessionStore.prototype.save = function(code) {
// Don't store a just repeated session
if (code === this.getLast()) { return; }
this._sessions.push(code);
if (this._sessions.length > this._sessionLimit) {
this._sessions.shift();
}
this._currentSessionIndex = this._sessions.length - 1;
this._storeSessions();
};
/**
* Get the previous session in the history
* @return {String}
*/
SessionStore.prototype.getPrevious = function() {
if (!this._sessions.length) { return ''; }
--this._currentSessionIndex;
if (this._currentSessionIndex < 0) {
this._currentSessionIndex = this._sessions.length - 1;
}
return this._sessions[this._currentSessionIndex];
};
/**
* Get the next session in the history
* @return {String}
*/
SessionStore.prototype.getNext = function() {
if (!this._sessions.length) { return ''; }
++this._currentSessionIndex;
if (this._currentSessionIndex === this._sessions.length) {
this._currentSessionIndex = 0;
}
return this._sessions[this._currentSessionIndex];
};
/**
* @private
*/
SessionStore.prototype._storeSessions = function() {
if (!window.localStorage) { return; }
// TODO: Maybe async this if it slows the UI
window.localStorage.setItem(this._dataKey, JSON.stringify(this._sessions));
};
/**
* @private
* @return {String[]}
*/
SessionStore.prototype._getAllSessions = function() {
if (!window.localStorage) { return []; }
var sessions = window.localStorage.getItem(this._dataKey);
var legacySession;
if (!sessions || !sessions.length) {
legacySession = this._getLegacySession();
return legacySession ? [legacySession] : [];
}
try {
return JSON.parse(sessions);
} catch (e) {
return [];
}
};
/**
* The old sessions used a 'code' key
* @private
* @return {?String}
*/
SessionStore.prototype._getLegacySession = function() {
return window.localStorage.getItem('code');
};
module.exports = SessionStore;