UNPKG

@cch137/format-utils

Version:

A collection of utility modules for formatting and processing data

91 lines (90 loc) 2.32 kB
export default class BigMap { static MAX_SIZE = 2 ** 24; segs = []; constructor(entries) { if (entries) { const _entries = [...entries]; const parts = []; while (_entries.length > 0) { parts.push(_entries.splice(0, BigMap.MAX_SIZE)); } } } get(key) { for (const map of this.segs) { if (map.has(key)) return map.get(key); } } has(key) { for (const map of this.segs) { if (map.has(key)) return true; } return false; } set(key, value) { let map = this.segs.at(-1); if (!map || map.size === BigMap.MAX_SIZE) { map = new Map(); this.segs.push(map); } map.set(key, value); return this; } delete(key) { const length = this.segs.length; for (let i = 0; i < length; i++) { const map = this.segs[i]; if (map.delete(key)) { if (map.size === 0) { this.segs.splice(this.segs.indexOf(map), 1); } else { const nextMap = this.segs[i + 1]; if (nextMap && nextMap.size > map.size) { this.segs[i] = nextMap; this.segs[i + 1] = map; } } return true; } } return false; } clear() { this.segs.splice(0); } forEach(callbackfn, thisArg) { for (const map of this.segs) { map.forEach(callbackfn, thisArg); } } *entries() { for (const map of this.segs) { yield* map.entries(); } } *keys() { for (const map of this.segs) { yield* map.keys(); } } *values() { for (const map of this.segs) { yield* map.values(); } } get size() { return this.segs.reduce((p, c) => p + c.size, 0); } get _size() { return this.segs.reduce((p, c) => p + BigInt(c.size), 0n); } get [Symbol.iterator]() { return () => this.entries(); } get [Symbol.toStringTag]() { return "BigMap"; } }