@beenotung/tslib
Version:
utils library in Typescript
86 lines (85 loc) • 2.08 kB
JavaScript
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.HashedArray = void 0;
const array_1 = require("./array");
const lang_1 = require("./lang");
/**
* <A> must be object.
* For string, number e.t.c use Set instead
* */
class HashedArray {
mapper;
array;
o;
constructor(mapper = x => x, array = [], o) {
this.array = array;
this.mapper = mapper;
if (o) {
this.o = o;
}
else {
const o = {};
array.forEach(x => (o[mapper(x)] = x));
this.o = o;
}
}
insert(x, key = this.mapper(x)) {
this.array.push(x);
this.o[key] = x;
return this;
}
replace(x, key = this.mapper(x)) {
const idx = this.array.findIndex(y => y === x);
if (idx !== -1) {
this.o[key] = this.array[idx] = x;
}
return this;
}
update(x, key = this.mapper(x)) {
Object.assign(this.o[key], x);
return this;
}
/**
* insert or replace
* */
upsert(x, key = this.mapper(x)) {
const y = this.o[key];
if ((0, lang_1.isDefined)(y)) {
Object.assign(y, x);
return this;
}
else {
return this.insert(x, key);
}
}
remove(x) {
return this.removeByKey(this.mapper(x));
}
removeByKey(key) {
(0, array_1.removeBy)(this.array, x => this.mapper(x) === key);
delete this.o[key];
return this;
}
isEmpty(isValid) {
return this.array.length === 0 || this.array.every(x => !isValid(x));
}
clear() {
this.o = {};
return (0, array_1.clearArray)(this.array);
}
get(key) {
return this.o[key];
}
has(key) {
return (0, lang_1.isDefined)(this.get(key));
}
set(key, x) {
return this.update(x, key);
}
static from(xs) {
const res = new HashedArray();
xs.forEach(x => res.insert(x));
return res;
}
}
exports.HashedArray = HashedArray;