UNPKG

@amaui/cache

Version:
96 lines (75 loc) 2.42 kB
import _defineProperty from "@babel/runtime/helpers/defineProperty"; import merge from '@amaui/utils/merge'; import copy from '@amaui/utils/copy'; import hash from '@amaui/utils/hash'; const unix = () => Math.floor(new Date().getTime() / 1000); const optionsDefault = { value: { copy: false }, add: { override: true } }; class AmauiCache { static get options() { return this.options_; } static set options(value) { this.options_ = merge(value, optionsDefault); } static add(value) { for (var _len = arguments.length, args = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) { args[_key - 1] = arguments[_key]; } const key = hash(args); if (!this.caches[key] || this.options.add.override) { const value_ = this.options.value.copy ? copy(value) : value; this.caches[key] = { value: value_, added_at: unix() }; return value_; } } static update(value) { for (var _len2 = arguments.length, args = new Array(_len2 > 1 ? _len2 - 1 : 0), _key2 = 1; _key2 < _len2; _key2++) { args[_key2 - 1] = arguments[_key2]; } const key = hash(args); if (this.caches[key]) { const value_ = this.options.value.copy ? copy(value) : value; this.caches[key].value = value_; this.caches[key].updated_at = unix(); return value_; } } static get() { for (var _len3 = arguments.length, args = new Array(_len3), _key3 = 0; _key3 < _len3; _key3++) { args[_key3] = arguments[_key3]; } const key = hash(args); if (this.caches[key]) return this.options.value.copy ? copy(this.caches[key].value) : this.caches[key].value; } static has() { for (var _len4 = arguments.length, args = new Array(_len4), _key4 = 0; _key4 < _len4; _key4++) { args[_key4] = arguments[_key4]; } const key = hash(args); return this.caches.hasOwnProperty(key); } static remove() { for (var _len5 = arguments.length, args = new Array(_len5), _key5 = 0; _key5 < _len5; _key5++) { args[_key5] = arguments[_key5]; } const key = hash(args); if (this.caches.hasOwnProperty(key)) delete this.caches[key]; } static reset() { this.caches = {}; this.options = optionsDefault; } } _defineProperty(AmauiCache, "caches", {}); _defineProperty(AmauiCache, "options_", optionsDefault); export default AmauiCache;