UNPKG

@t7/utils

Version:

Utility methods for T7 components.

107 lines (81 loc) 2.57 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.default = void 0; function _typeof(obj) { if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); } // ================================ // Flag for `localStorage` support. // ================================ var hasStorageSupport = function () { // Assume no support. var bool = false; // Used in the `try`. var key = 'TEST_KEY'; var val = 'TEST_VAL'; // Rigorously test for support. try { // Set the key/value. window.localStorage.setItem(key, val); // Are we able to read it? bool = window.localStorage.getItem(key) === val; // Delete the key/value. window.localStorage.removeItem(key); } catch (e) {} // Return the boolean. return bool; }(); // ======================= // Cache: Alias to object. // ======================= var cacheFallback = { clear: function clear() { for (var key in cache) { if (key !== 'clear' && cache.hasOwnProperty(key)) { delete cache[key]; } } } }; var cache = hasStorageSupport ? window.localStorage : cacheFallback; // ======================= // Cache: Clear key/value. // ======================= var clear = function clear() { cache.clear(); }; // ============== // Cache: Getter. // ============== var get = function get(key) { var data = cache[key]; // Exit, if no data. if (!data) { return; } try { // Attempt to parse. data = JSON.parse(data); } catch (e) { // Set to original. data = cache[key]; } return data; }; // ============== // Cache: Setter. // ============== var set = function set(key, data) { if (key === 'clear' || key === 'getItem' || key === 'key' || key === 'length' || key === 'removeItem' || key === 'setItem') { throw new Error('Cannot overwrite: window.localStorage.' + key); } if (_typeof(data) === 'object') { data = JSON.stringify(data); } cache[key] = data; }; // ========================== // Cache: Remove single item. // ========================== var remove = function remove(key) { delete cache[key]; }; // ============== // Export object. // ============== var storage = { clear: clear, get: get, remove: remove, set: set // Expose methods. }; var _default = storage; exports.default = _default;