|
| 1 | +import { HttpService } from "@rbxts/services"; |
| 2 | +import { IReadonlyStrictMap } from "interfaces/IReadonlyStrictMap"; |
| 3 | + |
| 4 | +export class StrictMap<K extends defined, V extends defined> implements IReadonlyStrictMap<K, V> { |
| 5 | + private map: Map<K, V>; |
| 6 | + private numberOfKeys = 0; |
| 7 | + |
| 8 | + public constructor( |
| 9 | + entries?: ReadonlyArray<[K, V]>, |
| 10 | + private readonly getMissingKeyErrorMessage?: (key: K) => string, |
| 11 | + ) { |
| 12 | + this.map = new Map<K, V>(entries ?? []); |
| 13 | + this.numberOfKeys = this.map.size(); |
| 14 | + } |
| 15 | + |
| 16 | + public clear() { |
| 17 | + this.map = new Map<K, V>(); |
| 18 | + this.numberOfKeys = 0; |
| 19 | + } |
| 20 | + |
| 21 | + public delete(key: K) { |
| 22 | + if (!this.map.has(key)) { |
| 23 | + return false; |
| 24 | + } |
| 25 | + |
| 26 | + this.numberOfKeys--; |
| 27 | + return this.map.delete(key); |
| 28 | + } |
| 29 | + |
| 30 | + public entries() { |
| 31 | + const result = new Array<[K, V]>(); |
| 32 | + for (const [key, value] of this.map) { |
| 33 | + result.push([key, value]); |
| 34 | + } |
| 35 | + return result; |
| 36 | + } |
| 37 | + |
| 38 | + public forEach(callbackfn: (value: V, key: K, self: this) => void) { |
| 39 | + this.map.forEach((value, key) => callbackfn(value, key, this)); |
| 40 | + } |
| 41 | + |
| 42 | + public has(key: K) { |
| 43 | + return this.map.has(key); |
| 44 | + } |
| 45 | + |
| 46 | + public isEmpty() { |
| 47 | + return this.numberOfKeys === 0; |
| 48 | + } |
| 49 | + |
| 50 | + public keys() { |
| 51 | + const result = new Array<K>(); |
| 52 | + for (const [key] of this.map) { |
| 53 | + result.push(key); |
| 54 | + } |
| 55 | + return result; |
| 56 | + } |
| 57 | + |
| 58 | + public mustGet(key: K) { |
| 59 | + const value = this.map.get(key); |
| 60 | + if (value === undefined) { |
| 61 | + if (this.getMissingKeyErrorMessage !== undefined) { |
| 62 | + throw this.getMissingKeyErrorMessage(key); |
| 63 | + } else { |
| 64 | + throw `Attempt to index missing value for key: ${key}`; |
| 65 | + } |
| 66 | + } |
| 67 | + |
| 68 | + return value; |
| 69 | + } |
| 70 | + |
| 71 | + public set(key: K, value: V) { |
| 72 | + if (!this.map.has(key)) { |
| 73 | + this.numberOfKeys++; |
| 74 | + } |
| 75 | + |
| 76 | + this.map.set(key, value); |
| 77 | + } |
| 78 | + |
| 79 | + public size() { |
| 80 | + return this.numberOfKeys; |
| 81 | + } |
| 82 | + |
| 83 | + public toReadonlyMap(): ReadonlyMap<K, V> { |
| 84 | + return new ReadonlyMap(this.entries()); |
| 85 | + } |
| 86 | + |
| 87 | + public toString() { |
| 88 | + return HttpService.JSONEncode(this.map); |
| 89 | + } |
| 90 | + |
| 91 | + public values() { |
| 92 | + const result = new Array<V>(); |
| 93 | + for (const [, value] of this.map) { |
| 94 | + result.push(value); |
| 95 | + } |
| 96 | + return result; |
| 97 | + } |
| 98 | +} |
0 commit comments