remember-js
Version:
A simple program used to remember and redo program operations
46 lines (42 loc) • 1.28 kB
JavaScript
;
var MemoryStorage = require('./MemoryStorage');
function Storage(storeId, storage) {
this.storeId = storeId;
storage = storage || new MemoryStorage();
if (!storage || typeof storage.getItem !== 'function' || typeof storage.setItem !== 'function') {
throw new Error('The storage must have both getItem and setItem method.');
}
this.store = storage;
}
Storage.prototype = {
push: function push(request) {
var stored = this._getStoredData();
stored.push(request);
this._saveDataToStore(stored);
return stored.length;
},
peek: function peek(index) {
index = index || 0;
var stored = this._getStoredData();
return stored[index];
},
shift: function shift() {
var stored = this._getStoredData(),
request = stored.shift();
this._saveDataToStore(stored);
return request;
},
getLength: function getLength() {
return this._getStoredData().length;
},
clear: function clear() {
this._saveDataToStore([]);
},
_getStoredData: function _getStoredData() {
return JSON.parse(this.store.getItem(this.storeId) || JSON.stringify('')) || [];
},
_saveDataToStore: function _saveDataToStore(data) {
this.store.setItem(this.storeId, JSON.stringify(data));
}
};
module.exports = Storage;