@beenotung/tslib
Version:
utils library in Typescript
124 lines (123 loc) • 3.01 kB
JavaScript
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.KVMap = void 0;
/**
* A Map that can do normal and reversed operations
* */
const array_1 = require("./array");
class KVMap {
[Symbol.toStringTag] = 'KVMap';
kvMap;
vkMap;
constructor() {
this.kvMap = new Map();
this.vkMap = new Map();
}
get size() {
return this.keySize;
}
get keySize() {
return this.kvMap.size;
}
get valueSize() {
return this.vkMap.size;
}
clear() {
this.kvMap.clear();
this.vkMap.clear();
}
delete(key) {
return this.deleteKey(key);
}
deleteKey(key) {
if (this.kvMap.has(key)) {
const value = this.kvMap.get(key);
const keys = this.vkMap.get(value) || [];
(0, array_1.remove)(keys, key);
}
return this.kvMap.delete(key);
}
deleteValue(value) {
if (this.vkMap.has(value)) {
const keys = this.vkMap.get(value);
keys.forEach(key => this.kvMap.delete(key));
}
return this.vkMap.delete(value);
}
forEach(callbackfn, thisArg) {
this.forEachKV(callbackfn, thisArg);
}
forEachKV(callbackfn, thisArg) {
this.kvMap.forEach(callbackfn, thisArg);
}
forEachVKs(callbackfn, thisArg) {
this.vkMap.forEach(callbackfn, thisArg);
}
get(key) {
return this.getValue(key);
}
getValue(key) {
return this.kvMap.get(key);
}
getKeys(value) {
return this.vkMap.get(value) || [];
}
has(key) {
return this.hasKey(key);
}
hasKey(key) {
return this.kvMap.has(key);
}
hasValue(value) {
return this.vkMap.has(value) && this.vkMap.get(value).length > 0;
}
set(key, value) {
if (this.hasKey(key)) {
this.deleteKey(key);
}
this.kvMap.set(key, value);
if (this.vkMap.has(value)) {
const keys = this.vkMap.get(value);
if (keys.indexOf(key) === -1) {
keys.push(key);
}
}
else {
this.vkMap.set(value, [key]);
}
return this;
}
[Symbol.iterator]() {
return this.kvMap[Symbol.iterator]();
}
entries() {
return this.kvEntries();
}
kvEntries() {
return this.kvMap.entries();
}
vkEntries() {
return this.vkMap.entries();
}
keys() {
return this.kvMap.keys();
}
values() {
return this.kvMap.values();
}
}
exports.KVMap = KVMap;
// function checkType<K, V>(map: Map<K, V>) {
// }
//
// checkType<string, string>({} as any as KVMap<string, string>);
(function (KVMap) {
function fromMap(map) {
const res = new KVMap();
map.forEach((value, key) => {
res.set(key, value);
});
return res;
}
KVMap.fromMap = fromMap;
})(KVMap || (exports.KVMap = KVMap = {}));