microsoft/typespec

Public

mirrored from https://github.com/microsoft/typespecAvailable

CodeCommitsIssuesPull requestsActionsInsightsSecurity
copilot/enable-backcompat-top-parameter-another-one

Branches

Tags

  • No tags available.
0Branches0Tags
Go to file
Add file
Code

Clone

HTTPS

Download ZIP

packages/asset-emitter/src/custom-key-map.ts

53lines · modecode

1/**
2 * This is a map type that allows providing a custom keyer function. The keyer
3 * function returns a string that is used to look up in the map. This is useful
4 * for implementing maps that look up based on an arbitrary number of keys.
5 *
6 * For example, to look up in a map with a [ObjA, ObjB)] tuple, such that tuples
7 * with identical values (but not necessarily identical tuples!) create an
8 * object keyer for each of the objects:
9 *
10 * const aKeyer = CustomKeyMap.objectKeyer();
11 * const bKeyer = CUstomKeyMap.objectKeyer();
12 *
13 * And compose these into a tuple keyer to use when instantiating the custom key
14 * map:
15 *
16 * const tupleKeyer = ([a, b]) => `${aKeyer.getKey(a)}-${bKeyer.getKey(b)}`;
17 * const map = new CustomKeyMap(tupleKeyer);
18 *
19 */
20export class CustomKeyMap<K extends readonly any[], V> {
21 #items = new Map<string, V>();
22 #keyer;
23
24 constructor(keyer: (args: K) => string) {
25 this.#keyer = keyer;
26 }
27
28 get(items: K): V | undefined {
29 return this.#items.get(this.#keyer(items));
30 }
31
32 set(items: K, value: V): void {
33 const key = this.#keyer(items);
34 this.#items.set(key, value);
35 }
36
37 static objectKeyer() {
38 const knownKeys = new WeakMap<object, number>();
39 let count = 0;
40 return {
41 getKey(o: object) {
42 if (knownKeys.has(o)) {
43 return knownKeys.get(o);
44 }
45
46 const key = count;
47 count++;
48 knownKeys.set(o, key);
49 return key;
50 },
51 };
52 }
53}
54