MCPcopy Create free account
hub / github.com/subquery/subql / BlockHeightMap

Class BlockHeightMap

packages/node-core/src/utils/blockHeightMap.ts:12–114  ·  view source on GitHub ↗

Source from the content-addressed store, hash-verified

10}
11
12export class BlockHeightMap<T> {
13 #map: Map<number, T>;
14
15 constructor(initialValues: Map<number, T>) {
16 // Ensure the values are sorted by key
17 this.#map = new Map([...initialValues.entries()].sort((a, b) => a[0] - b[0]));
18 }
19
20 getAll(): Map<number, T> {
21 return this.#map;
22 }
23
24 get(height: number): T {
25 const details = this.getDetails(height);
26
27 if (details === undefined) {
28 throw new EntryNotFoundError(height);
29 }
30
31 return details.value;
32 }
33
34 // Same as get but wont throw when there is nothing in the block range
35 getSafe(height: number): T | undefined {
36 try {
37 return this.get(height);
38 } catch (e) {
39 return undefined;
40 }
41 }
42
43 getDetails(height: number): GetRange<T> | undefined {
44 let result: GetRange<T> | undefined;
45
46 const arr = [...this.#map.entries()];
47
48 for (let i = 0; i < arr.length; i++) {
49 const [currentHeight, value] = arr[i];
50 const nextStart = arr[i + 1]?.[0];
51 const r = {
52 value,
53 startHeight: currentHeight,
54 endHeight: nextStart ? nextStart - 1 : undefined,
55 };
56
57 if (currentHeight === height) {
58 result = r;
59 break;
60 }
61 if (currentHeight <= height) {
62 result = r;
63 }
64
65 if (currentHeight > height) {
66 break;
67 }
68 }
69

Callers

nothing calls this directly

Calls

no outgoing calls

Tested by

no test coverage detected