typescript / intermediate
Snippet
Accelerating Search Operations by Indexing Arrays with Map Instances
Transforming linear array iterations into Map lookups trades memory for performance, improving key search complexity from O(N) linear time to O(1) constant time.
snippet.ts
typescript
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
interface UserRecord {id: number;email: string;}class UserIndex {private indexMap = new Map<number, UserRecord>();constructor(records: UserRecord[]) {for (const record of records) {this.indexMap.set(record.id, record);}}public findById(id: number): UserRecord | undefined {return this.indexMap.get(id);}}
Breakdown
1
private indexMap = new Map<number, UserRecord>();
Encapsulates a strongly typed Map data structure to hold key-value index entries.
2
this.indexMap.set(record.id, record);
Populates the index during initialization for constant-time downstream retrieval.
3
return this.indexMap.get(id);
Performs an O(1) lookup to fetch records instantaneously regardless of array size.