Skip to content

Instantly share code, notes, and snippets.

@drzhbe
Created July 17, 2014 11:45
Show Gist options
  • Save drzhbe/2a6a9e8130ef276f2572 to your computer and use it in GitHub Desktop.
Save drzhbe/2a6a9e8130ef276f2572 to your computer and use it in GitHub Desktop.
How to interact with key-value storage (localStorage) like a stack
/**
* Добавить в стэк listName значение value.
* При в storage будет храниться ключ ${listName}_last со значением индекса последнего элемента в этом списке.
* Новое значение сериализованное в JSON добавится в storage с ключом ${listName}_last + 1.
*
* Пример:
* В списке listName=log есть 3 элемента, storage будет выглядеть так:
* {
* 'log_last': '2',
* 'log_0': '{...}',
* 'log_1': '{...}',
* 'log_2': '{...},
* }
* После вызова storage.push('log', value) произойдет следующее:
* 1. значение в поле 'log_last' увеличится на 1
* 2. добавится запись 'log_3' со значением value
*
* @param {String} listName
* @param {Object} value
*/
Storage.prototype.push = function(listName, value) {
var lastIndexKey = listName + '_last';
if (this.storage[lastIndexKey] == null) {
this.storage[lastIndexKey] = 0;
} else {
this.storage[lastIndexKey] = Number(this.storage[lastIndexKey]) + 1;
}
this.storage[ listName + '_' + this.storage[lastIndexKey] ] = JSON.stringify(value);
};
/**
* Вытащить из стэка listName последний элемент и вернуть его.
*
* @param {String} listName
* @returns {Object|undefined}
*/
Storage.prototype.pop = function(listName) {
var lastIndexKey = listName + '_last';
var lastElementKey = listName + '_' + this.storage[lastIndexKey];
var lastElement = this.storage[lastElementKey];
if (lastElement != null) {
lastElement = JSON.parse( lastElement );
delete this.storage[lastElementKey];
this.storage[lastIndexKey] = Number(this.storage[lastIndexKey]) - 1;
return lastElement;
}
};
/**
* Удалить все записи с ключом key из storage.
*
* @param {String} key
*/
Storage.prototype.clear = function(key) {
var last = Number(this.storage[key + '_last']);
for (var i = 0; i < last; i++) {
delete this.storage[key + '_' + i];
}
delete this.storage[key + '_last'];
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment