scats
Version:
Useful scala classes in typescript
114 lines (113 loc) • 2.9 kB
JavaScript
import { AbstractMap } from '../abstract-map.js';
import * as immutable from '../hashmap.js';
export class HashMap extends AbstractMap {
constructor(map = new Map()) {
super(map);
}
fromArray(array) {
return HashMap.of(...array);
}
static of(...values) {
return new HashMap(new Map(values));
}
static from(values) {
return HashMap.of(...Array.from(values));
}
addAll(values) {
for (const [key, value] of values) {
this.map.set(key, value);
}
return this;
}
updateWith(key) {
const previousValue = this.get(key);
return (remappingFunction) => {
const nextValue = remappingFunction(previousValue);
if (previousValue.isEmpty && nextValue.isEmpty) {
return nextValue;
}
else if (previousValue.isDefined && nextValue.isEmpty) {
this.remove(key);
return nextValue;
}
else {
this.update(key, nextValue.get);
return nextValue;
}
};
}
subtractAll(values) {
if (this.isEmpty) {
return this;
}
for (const key of values) {
this.map.delete(key);
if (this.isEmpty) {
return this;
}
}
return this;
}
clear() {
this.map.clear();
}
clone() {
const contentClone = new Map(this.map);
return new HashMap(contentClone);
}
filterInPlace(p) {
if (this.nonEmpty) {
const entries = this.entries;
entries.foreach(e => {
if (!p(e)) {
this.remove(e[0]);
}
});
}
return this;
}
mapValuesInPlace(f) {
if (this.nonEmpty) {
const entries = this.entries;
entries.foreach(e => {
this.update(e[0], f(e));
});
}
return this;
}
getOrElseUpdate(key, defaultValue) {
return this.get(key).getOrElse(() => {
const newValue = defaultValue();
this.map.set(key, newValue);
return newValue;
});
}
set(key, value) {
this.map.set(key, value);
return this;
}
put(key, value) {
const res = this.get(key);
this.map.set(key, value);
return res;
}
remove(key) {
const res = this.get(key);
this.subtractOne(key);
return res;
}
update(key, value) {
this.map.set(key, value);
}
addOne(elem) {
this.map.set(elem[0], elem[1]);
return this;
}
subtractOne(key) {
this.map.delete(key);
return this;
}
get toImmutable() {
return immutable.HashMap.of(...this.map.entries());
}
}