Created
July 18, 2014 05:35
-
-
Save drzhbe/cda1f853f699622585e7 to your computer and use it in GitHub Desktop.
How to interact with key-value storage (localStorage) like a queue
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Функции для работы со storage, как с очередью. | |
*/ | |
/** | |
* Очистить старые записи. | |
* @param tailIndexValue | |
* @param nextIndexValue | |
*/ | |
function free(tailIndexValue, nextIndexValue) { | |
var currentTimestamp = Number(new Date()); | |
while (tailIndexValue != nextIndexValue) { | |
// @TODO: использовать dequeue и двигать storage[tailValueKey] и когда он совпадет с storage[nextValueKey] — скинуть их на дефолты | |
} | |
} | |
module.exports = { | |
enqueue: function(value) { | |
var tailIndexValue = Number(this.storage[this.tailIndexKey]); | |
var nextIndexValue = Number(this.storage[this.nextIndexKey]); | |
this.storage[this.name + '_' + nextIndexValue] = JSON.stringify(value); | |
this.storage[this.nextIndexKey] = nextIndexValue + 1; | |
if (nextIndexValue - tailIndexValue > this.size) { | |
free(tailIndexValue, nextIndexValue); | |
} | |
}, | |
dequeue: function() { | |
var tailIndexValue = Number(this.storage[this.tailIndexKey]); | |
var tailValueKey = this.name + '_' + tailIndexValue; | |
var tailValue = this.storage[tailValueKey]; | |
if (tailValue) { | |
tailValue = JSON.parse(tailValue); | |
delete this.storage[tailValueKey]; | |
this.storage[this.tailIndexKey] = tailIndexValue + 1; | |
if (this.storage[this.tailIndexKey] == this.storage[this.nextIndexKey]) { | |
this.storage[this.tailIndexKey] = this.storage[this.nextIndexKey] = 0; | |
} | |
return tailValue; | |
} | |
} | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment