javascript / expert
Snippet
Dynamisches Sparse-Array-Index-Mapping und Mutationstracking in Svelte
Sparse-Dense-Array-Paare (Sparse Sets) ermöglichen O(1)-Zugriffe, Einfügungen und Löschungen bei dichter Array-Iterierbarkeit – ideal für dynamische ID-basierte Listen-Updates.
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
Erklärung
1
this.sparse[key] = idx;
Mappt beliebigen numerischen Key direkt auf die Position im zusammenhängenden dichten Array.
2
const last = this.dense.pop();
Tauscht das letzte Element in die gelöschte Lücke zur Erhaltung fixer O(1)-Performance.
3
delete this.sparse[key];
Löscht den Sparse-Mapping-Eintrag beim Entfernen des Elements.