UNPKG

s2-tools

Version:

A collection of geospatial tools primarily designed for WGS84, Web Mercator, and S2.

72 lines 2.05 kB
/** * # Cache System * * ## Description * A cache of values with a max size to ensure that too much old data is not stored. * * ## Usage * * ```ts * import { Cache } from 's2-tools'; * * const onDelete = (key: string, value: string) => { * console.log(`Deleted key ${key} with value ${value}`); * }; * const cache = new Cache<string, string>(10, onDelete); * cache.set('key', 'value'); * console.log(cache.get('key')); // 'value' * cache.delete('key'); * ``` */ export class Cache extends Map { maxSize; onDelete; order = []; /** * @param maxSize - the max size of the cache before dumping old data * @param onDelete - if provided, will be called when a value is removed */ constructor(maxSize, onDelete) { super(); this.maxSize = maxSize; this.onDelete = onDelete; } /** * @param key - the offset position in the data * @param value - the value to store * @returns this */ set(key, value) { // if key exists, we just update the place in the array if (super.has(key)) this.order.splice(this.order.indexOf(key), 1); // add the key to the start of the array this.order.unshift(key); while (this.order.length > this.maxSize) this.delete(this.order.pop()); return super.set(key, value); } /** * @param key - the offset position in the data * @returns - the value if found */ get(key) { // update the place in the array and than get if (super.has(key)) { this.order.splice(this.order.indexOf(key), 1); this.order.unshift(key); } return super.get(key); } /** * @param key - the offset position in the data * @returns - true if found */ delete(key) { const value = super.get(key); if (value !== undefined && this.onDelete !== undefined) this.onDelete(key, value); return super.delete(key); } } //# sourceMappingURL=cache.js.map