counted-storage
Version:
Lightweight lib to work with the local storage implementing lifetime based on how many times the item was used
1 lines • 2.54 kB
JavaScript
!function(e,t){if("object"==typeof exports&&"object"==typeof module)module.exports=t();else if("function"==typeof define&&define.amd)define([],t);else{var r=t();for(var o in r)("object"==typeof exports?exports:e)[o]=r[o]}}(window,function(){return function(e){var t={};function r(o){if(t[o])return t[o].exports;var n=t[o]={i:o,l:!1,exports:{}};return e[o].call(n.exports,n,n.exports,r),n.l=!0,n.exports}return r.m=e,r.c=t,r.d=function(e,t,o){r.o(e,t)||Object.defineProperty(e,t,{enumerable:!0,get:o})},r.r=function(e){"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})},r.t=function(e,t){if(1&t&&(e=r(e)),8&t)return e;if(4&t&&"object"==typeof e&&e&&e.__esModule)return e;var o=Object.create(null);if(r.r(o),Object.defineProperty(o,"default",{enumerable:!0,value:e}),2&t&&"string"!=typeof e)for(var n in e)r.d(o,n,function(t){return e[t]}.bind(null,n));return o},r.n=function(e){var t=e&&e.__esModule?function(){return e.default}:function(){return e};return r.d(t,"a",t),t},r.o=function(e,t){return Object.prototype.hasOwnProperty.call(e,t)},r.p="",r(r.s=0)}([function(e,t,r){"use strict";r.r(t);t.default=function(e,t){return function(){try{const e="counted-storage-test";return window.localStorage.setItem(e,e),window.localStorage.removeItem(e),!0}catch(e){return console.error("Local Storage is not supported, Counted Storage can't be initialized"),!1}}()&&function(e){const t=null!=e&&"string"==typeof e&&e.length>0;return t||console.error("You must provide a valid namespace for the counted storage"),t}(e)?new class{constructor(e,t=1){this.namespace=e,this.defaultValidity=t,this.storage=window.localStorage}get(e,t=null){const r=this.buildKey(e),o=this.storage.getItem(r);if(null==o)return t;const n=JSON.parse(o);return n.use_count>=n.use_validity?(this.remove(e),t):(n.use_count++,this.storage.setItem(r,JSON.stringify(n)),n.data)}getAll(){const e=Object.keys(this.storage).filter(e=>e.startsWith(this.namespace)).map(e=>{const t=JSON.parse(this.storage.getItem(e));return t.key=e,t}),t={};return e.filter(e=>e.use_count<e.use_validity).forEach(e=>t[e.key]=e.data),t}set(e,t,r=this.defaultValidity){const o={use_count:0,use_validity:r,data:t};this.storage.setItem(this.buildKey(e),JSON.stringify(o))}remove(e){this.storage.removeItem(this.buildKey(e))}clear(){Object.keys(this.storage).filter(e=>e.startsWith(this.namespace)).map(e=>this.storage.removeItem(e))}buildKey(e){return`${this.namespace}_${e}`}}(e,t):null}}])});