timed-kvs
Version:
Lightweight Key-value storage with built-in TTL expiration management
1 lines • 2.49 kB
JavaScript
var TimedKVS=function(t){"use strict";var e,i=function(){function t(){this.latest=null,this.items={},this.length=0}return t.prototype.get=function(t){var e=this.getItem(t);if(e)return e.value},t.prototype.set=function(t,e){this.setItem(t,{value:e})},t.prototype.getItem=function(t){var e=this.items[t];if(e&&!e.deleted)return e},t.prototype.setItem=function(t,e){var i=e;this.delete(t),this.items[t]=i,this.length++,i.key=t;var r=this.latest;r&&(i.next=r.deleted?r.next:r),this.latest=i},t.prototype.size=function(){return this.length},t.prototype.shrink=function(t){for(var e=this.latest;e;){if(0>=t)return void this.truncate(e);e.deleted||t--,e=e.next}},t.prototype.delete=function(t){var e=this.getItem(t);e&&this._delete(e)},t.prototype._delete=function(t){if(t){t.deleted||(delete this.items[t.key],this.length--,t.key=t.value=null,t.deleted=!0);for(var e=t.next;e&&e.deleted;)e=t.next=e.next}},t.prototype.truncate=function(t){for(var e=t;e;)this._delete(e),e=e.next},t.prototype.all=function(){for(var t=[],e=this.latest;e;){if(!e.deleted){var i=this.getItem(e.key);i&&t.push(i)}e=e.next}return t.reverse()},t.prototype.keys=function(){return this.all().map((function(t){return t.key}))},t.prototype.values=function(){return this.all().map((function(t){return t.value}))},t}(),r=(e=function(t,i){return e=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var i in e)Object.prototype.hasOwnProperty.call(e,i)&&(t[i]=e[i])},e(t,i)},function(t,i){if("function"!=typeof i&&null!==i)throw new TypeError("Class extends value "+String(i)+" is not a constructor or null");function r(){this.constructor=t}e(t,i),t.prototype=null===i?Object.create(i):(r.prototype=i.prototype,new r)}),n=function(t){function e(e){var i=t.call(this)||this,r=e||{},n=r.expires,o=r.maxItems;return i.expires=n>0&&+n||0,i.maxItems=o>0&&+o||0,i}return r(e,t),e.prototype.getItem=function(e){var i=this.expires,r=t.prototype.getItem.call(this,e);if(r){if(i)if(Date.now()>r.ttl)return void this.truncate(r);return r}},e.prototype.setItem=function(e,i){var r=this,n=this.expires,o=this.maxItems;if(n){if(this.firstKey)!this.getItem(this.firstKey)&&(this.firstKey=void 0);else this.firstKey=e;var s=Date.now();i.ttl=s+n}if(t.prototype.setItem.call(this,e,i),o){if(this.gcTimeout||o>=this.size())return;var u=Math.min(o,1e3);this.gcTimeout=setTimeout((function(){r.shrink(o),delete r.gcTimeout}),u)}},e}(i);return t.TimedKVS=n,n}("undefined"!=typeof exports?exports:{});