Files
j2s/lib/src/stdlib/classes/map.ts
2025-01-24 22:37:52 +02:00

124 lines
2.7 KiB
TypeScript

import { Array } from "../values/array.ts";
import { func, map } from "../primordials.ts";
import { symbols } from "../utils.ts";
export class Map<K, V> {
#map: InstanceType<typeof map>;
public get size() {
return this.#map.size();
}
public get(key: K): V {
return this.#map.get(key);
}
public has(key: K): boolean {
return this.#map.has(key);
}
public set(key: K, val: V) {
this.#map.set(key, val);
return this;
}
public delete(key: K): boolean {
if (!this.#map.has(key)) return false;
else {
this.#map.delete(key);
return true;
}
}
public clear() {
this.#map.clear();
}
public keys(): K[] {
return this.#map.keys();
}
public values(): V[] {
const res = this.#map.keys();
for (let i = 0; i < res.length; i++) {
res[i] = this.#map.get(res[i]);
}
return res;
}
public entries(): [K, V][] {
const res = this.#map.keys();
for (let i = 0; i < res.length; i++) {
res[i] = [res[i], this.#map.get(res[i])];
}
return res;
}
public forEach(cb: Function, self?: any) {
const entries = this.entries();
for (let i = 0; i < entries.length; i++) {
func.invoke(cb, self, [entries[i][1], entries[i][0], this]);
}
}
public [symbols.iterator](): Iterator<[K, V]> {
return func.invoke(Array.prototype[symbols.iterator], this.entries(), []) as any;
}
public constructor(iterable?: Iterable<[K, V]>) {
const _map = this.#map = new map();
if (iterable != null) {
if (Array.isArray(iterable)) {
for (let i = 0; i < iterable.length; i++) {
if (!(i in iterable)) continue;
_map.set(iterable[i][0], iterable[i][1]);
}
}
else {
const it = (iterable as any)[symbols.iterator]();
for (let val = it.next(); !val.done; val = it.next()) {
_map.set(val.value[0], val.value[1]);
}
}
}
}
}
export class WeakMap<K, V> {
#map: InstanceType<typeof map>;
public get(key: K): V {
return this.#map.get(key);
}
public has(key: K): boolean {
return this.#map.has(key);
}
public set(key: K, val: V) {
this.#map.set(key, val);
return this;
}
public delete(key: K): boolean {
if (!this.#map.has(key)) return false;
else {
this.#map.delete(key);
return true;
}
}
public clear() {
this.#map.clear();
}
public constructor(iterable?: Iterable<[K, V]>) {
const _map = this.#map = new map(true);
if (iterable != null) {
if (Array.isArray(iterable)) {
for (let i = 0; i < iterable.length; i++) {
if (!(i in iterable)) continue;
_map.set(iterable[i][0], iterable[i][1]);
}
}
else {
const it = (iterable as any)[symbols.iterator]();
for (let val = it.next(); !val.done; val = it.next()) {
_map.set(val.value[0], val.value[1]);
}
}
}
}
}