|
| 1 | +import { Account, internal } from '@algorandfoundation/algorand-typescript' |
| 2 | +import { encodingUtil } from '@algorandfoundation/puya-ts' |
| 3 | +import { DeliberateAny } from '../typescript-helpers' |
| 4 | + |
| 5 | +type Primitive = number | bigint | string | boolean |
| 6 | +export abstract class CustomKeyMap<TKey, TValue> implements Map<TKey, TValue> { |
| 7 | + #keySerializer: (key: TKey) => Primitive |
| 8 | + #map = new Map<Primitive, [TKey, TValue]>() |
| 9 | + |
| 10 | + constructor(keySerializer: (key: TKey) => number | bigint | string) { |
| 11 | + this.#keySerializer = keySerializer |
| 12 | + } |
| 13 | + |
| 14 | + clear(): void { |
| 15 | + this.#map.clear() |
| 16 | + } |
| 17 | + delete(key: TKey): boolean { |
| 18 | + return this.#map.delete(this.#keySerializer(key)) |
| 19 | + } |
| 20 | + forEach(callbackfn: (value: TValue, key: TKey, map: Map<TKey, TValue>) => void, thisArg?: DeliberateAny): void { |
| 21 | + for (const [key, value] of this.#map.values()) { |
| 22 | + callbackfn.call(thisArg ?? this, value, key, this) |
| 23 | + } |
| 24 | + } |
| 25 | + get(key: TKey): TValue | undefined { |
| 26 | + return this.#map.get(this.#keySerializer(key))?.[1] |
| 27 | + } |
| 28 | + has(key: TKey): boolean { |
| 29 | + return this.#map.has(this.#keySerializer(key)) |
| 30 | + } |
| 31 | + set(key: TKey, value: TValue): this { |
| 32 | + this.#map.set(this.#keySerializer(key), [key, value]) |
| 33 | + return this |
| 34 | + } |
| 35 | + get size(): number { |
| 36 | + return this.#map.size |
| 37 | + } |
| 38 | + entries(): MapIterator<[TKey, TValue]> { |
| 39 | + return this.#map.values() |
| 40 | + } |
| 41 | + *keys(): MapIterator<TKey> { |
| 42 | + for (const [key] of this.#map.values()) { |
| 43 | + yield key |
| 44 | + } |
| 45 | + } |
| 46 | + *values(): MapIterator<TValue> { |
| 47 | + for (const [, value] of this.#map.values()) { |
| 48 | + yield value |
| 49 | + } |
| 50 | + } |
| 51 | + [Symbol.iterator](): MapIterator<[TKey, TValue]> { |
| 52 | + return this.#map.values() |
| 53 | + } |
| 54 | + get [Symbol.toStringTag](): string { |
| 55 | + return this.constructor.name |
| 56 | + } |
| 57 | +} |
| 58 | + |
| 59 | +export class AccountMap<TValue> extends CustomKeyMap<Account, TValue> { |
| 60 | + constructor() { |
| 61 | + super(AccountMap.getAddressStrFromAccount) |
| 62 | + } |
| 63 | + |
| 64 | + private static getAddressStrFromAccount = (acc: Account) => { |
| 65 | + return encodingUtil.uint8ArrayToHex(internal.primitives.BytesCls.fromCompat(acc.bytes).asUint8Array()) |
| 66 | + } |
| 67 | +} |
0 commit comments