pitaya-launcher/js/util/cache.js

34 lines
732 B
JavaScript

function Cache() {
this._store = {};
}
Cache.prototype.get = function(key) {
key = this._serialize(key);
return key in this._store ? this._store[key] : undefined;
};
Cache.prototype.set = function(key, value) {
key = this._serialize(key);
this._store[key] = value;
return this;
};
Cache.prototype._serialize = function(mixedKey) {
var json = JSON.stringify(mixedKey);
return this._hash(json);
};
Cache.prototype._hash = function(str) {
var hash = 0, i, chr, len;
if (str.length === 0) return hash;
for (i = 0, len = str.length; i < len; i++) {
chr = str.charCodeAt(i);
hash = ((hash << 5) - hash) + chr;
hash |= 0; // Convert to 32bit integer
}
return hash;
};
module.exports = Cache;