Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
78 changes: 78 additions & 0 deletions src/ImmutableSet.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,78 @@
export class ImmutableSet<T> implements ReadonlySet<T> {
#set: Set<T>;

constructor(values?: Iterable<T> | null) {
this.#set = values instanceof Set ? values : new Set(values);
}

[Symbol.iterator](): SetIterator<T> {
return this.#set[Symbol.iterator]();
}

get size(): number {
return this.#set.size;
}

has(value: T): boolean {
return this.#set.has(value);
}

keys(): SetIterator<T> {
return this.#set.keys();
}

values(): SetIterator<T> {
return this.#set.values();
}

entries(): SetIterator<[T, T]> {
return this.#set.entries();
}

forEach<TSelf>(
callbackfn: (value: T, value2: T, set: Set<T>) => void,
thisArg?: TSelf,
): void {
this.#set.forEach(callbackfn, thisArg);
}

union<U>(other: ReadonlySetLike<U>): Set<T | U> {
return this.#set.union(other);
}

intersection<U>(other: ReadonlySet<U>): Set<T & U> {
return this.#set.intersection(other);
}

difference<U>(other: ReadonlySet<U>): Set<T> {
return this.#set.difference(other);
}

symmetricDifference<U>(other: ReadonlySet<U>): Set<T | U> {
return this.#set.symmetricDifference(other);
}

isSubsetOf<U>(other: ReadonlySet<U>): boolean {
return this.#set.isSubsetOf(other);
}

isSupersetOf<U>(other: ReadonlySet<U>): boolean {
return this.#set.isSupersetOf(other);
}

isDisjointFrom<U>(other: ReadonlySet<U>): boolean {
return this.#set.isDisjointFrom(other);
}

get [Symbol.toStringTag](): string {
return "ImmutableSet";
}

[Symbol.for("nodejs.util.inspect.custom")](): string {
return `ImmutableSet(${this.size}) { ${
[...this.#set]
.map((value) => Deno.inspect(value, { colors: !Deno.noColor }))
.join(", ")
} }`;
}
}
16 changes: 10 additions & 6 deletions src/MultiDict.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
import { ImmutableSet } from "./ImmutableSet.ts";

/**
* A multi-key multi-value map implementation.
*
Expand Down Expand Up @@ -82,8 +84,12 @@ export class MultiDict<K, V>
*/
get(key: K): ReadonlySet<V> | undefined;
get(key: V): ReadonlySet<K> | undefined;
get(key: K | V) {
return this.#map.get(key) as ReadonlySet<K | V> | undefined;
get(key: K | V): ReadonlySet<K | V> | undefined {
const set = this.#map.get(key);

if (set) {
return new ImmutableSet(set);
}
}

/**
Expand Down Expand Up @@ -111,10 +117,8 @@ export class MultiDict<K, V>
}

#set(key: K | V, value: K | V) {
const set = this.#map.get(key) ?? new Set();
set.add(value);

this.#map.set(key, set);
this.#map.get(key)?.add(value) ??
this.#map.set(key, new Set([value]));

return this;
}
Expand Down