node-apparatus
Version:
A mix of common components needed for awesome node experience
93 lines • 3.05 kB
JavaScript
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.SortedMap = void 0;
/**
* A sorted map that maintains the order associated with elements.
*/
class SortedMap {
constructor(map = new Map(), sortedKeys = new Map()) {
this.map = map;
this.sortedKeys = sortedKeys;
/**
* The maximum order of the elements in the map.
*/
this.maxOrder = Number.MIN_SAFE_INTEGER;
}
/**
* Set a key-value pair in the map.
* @param key The key of the element.
* @param value The value of the element.
* @param order The order of the element or undefined if you want to maintain insertion order.
* @throws If the order is not a valid 32 bit finite number.
* @returns The map instance.
*/
set(key, value, order = undefined) {
if (order !== undefined && (Number.isNaN(order) || (!Number.isSafeInteger(order))))
throw new Error('Order must be a valid 32 bit finite number');
if (order !== undefined) {
this.maxOrder = Math.max(this.maxOrder, order);
}
else {
order = ++this.maxOrder;
}
this.map.set(key, value);
this.sortedKeys.set(key, order);
}
/**
* Get the value of a key in the map.
* @param key The key of the element.
* @returns The value of the element or undefined if the key does not exist.
*/
get(key) {
return this.map.get(key);
}
/**
* Sorts the map based on the order of the elements.
* @returns A new map instance with the elements sorted based on the order.
* @remarks This method does not modify the original map.
* @remarks This method has a time complexity of O(n log n).
* @remarks This method has a space complexity of O(n).
* @remarks This method is not stable.
*/
sort() {
const sortedKeys = Array.from(this.sortedKeys.entries())
.sort((a, b) => a[1] - b[1]);
const sortedMap = new Map();
for (const [key, order] of sortedKeys) {
const value = this.map.get(key);
if (value === undefined)
continue;
sortedMap.set(key, value);
}
return sortedMap;
}
/**
* Check if a key exists in the map.
* @param key The key of the element.
* @returns True if the key exists in the map, false otherwise.
*/
has(key) {
return this.map.has(key) && this.sortedKeys.has(key);
}
/**
* Delete a key from the map.
* @param key The key of the element.
* @returns True if the key was deleted, false otherwise.
*/
delete(key) {
return this.map.delete(key) && this.sortedKeys.delete(key);
}
/**
* Clears the map.
*/
clear() {
this.map.clear();
this.sortedKeys.clear();
this.maxOrder = Number.MIN_SAFE_INTEGER;
}
[Symbol.dispose]() {
this.clear();
}
}
exports.SortedMap = SortedMap;
//# sourceMappingURL=sorted-map.js.map