javascript / expert
Snippet
Dynamic Sparse Array Index Mapping and Mutation Tracking in Svelte
Sparse-dense array pairs (sparse sets) enable O(1) lookups, insertions, and deletions with dense array iteration, ideal for dynamic ID-based list updates without array scans.
snippet.js
javascript
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
export class SparseIndexMap {constructor() {this.dense = [];this.sparse = [];}insert(key, value) {const idx = this.dense.length;this.dense.push({ key, value });this.sparse[key] = idx;}get(key) {const idx = this.sparse[key];return idx !== undefined && this.dense[idx]?.key === key ? this.dense[idx].value : undefined;}remove(key) {const idx = this.sparse[key];if (idx === undefined || this.dense[idx]?.key !== key) return false;const last = this.dense.pop();if (idx < this.dense.length) {this.dense[idx] = last;this.sparse[last.key] = idx;}delete this.sparse[key];return true;}}
svelte
Breakdown
1
this.sparse[key] = idx;
Maps arbitrary numeric key directly to contiguous dense index location.
2
const last = this.dense.pop();
Swaps last element into deleted slot to maintain cache-friendly dense array continuity in O(1).
3
delete this.sparse[key];
Clears sparse mapping lookup entry upon item removal.