UNPKG

@newdash/newdash

Version:

javascript/typescript utility library

113 lines (112 loc) 3.21 kB
"use strict"; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", { value: true }); const Hash_1 = __importDefault(require("./Hash")); /** * Gets the data for `map`. * * @private * @param {Object} map The map to query. * @param {string} key The reference key. * @returns {*} Returns the map data. */ function getMapData({ __data__ }, key) { const data = __data__; return isKeyable(key) ? data[typeof key === 'string' ? 'string' : 'hash'] : data.map; } /** * Checks if `value` is suitable for use as unique object key. * * @private * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is suitable, else `false`. */ function isKeyable(value) { const type = typeof value; return (type === 'string' || type === 'number' || type === 'symbol' || type === 'boolean') ? (value !== '__proto__') : (value === null); } class MapCache { /** * Creates a map cache object to store key-value pairs. * * @private * @constructor * @param {Array} [entries] The key-value pairs to cache. */ constructor(entries) { let index = -1; const length = entries == null ? 0 : entries.length; this.clear(); while (++index < length) { const entry = entries[index]; this.set(entry[0], entry[1]); } } /** * Removes all key-value entries from the map. * * @memberOf MapCache */ clear() { this.size = 0; this.__data__ = { 'hash': new Hash_1.default, 'map': new Map, 'string': new Hash_1.default }; } /** * Removes `key` and its value from the map. * * @memberOf MapCache * @param {string} key The key of the value to remove. * @returns {boolean} Returns `true` if the entry was removed, else `false`. */ delete(key) { const result = getMapData(this, key)['delete'](key); this.size -= result ? 1 : 0; return result; } /** * Gets the map value for `key`. * * @memberOf MapCache * @param {string} key The key of the value to get. * @returns {*} Returns the entry value. */ get(key) { return getMapData(this, key).get(key); } /** * Checks if a map value for `key` exists. * * @memberOf MapCache * @param {string} key The key of the entry to check. * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`. */ has(key) { return getMapData(this, key).has(key); } /** * Sets the map `key` to `value`. * * @memberOf MapCache * @param {string} key The key of the value to set. * @param {*} value The value to set. * @returns {Object} Returns the map cache instance. */ set(key, value) { const data = getMapData(this, key); const size = data.size; data.set(key, value); this.size += data.size == size ? 0 : 1; return this; } } exports.default = MapCache;