javascript / expert
Snippet
Effiziente Ringpuffer-Array-Manipulation in Svelte Keyed-Each-Blöcken
Ringpuffer halten Push-Operationen in konstanter Zeit ohne Garbage-Collection-Overhead durch Array-Reallokation und projizieren Ansichten für Svelte-Komponenten.
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
export class FixedRingBuffer {constructor(capacity) {this.buffer = new Array(capacity);this.capacity = capacity;this.head = 0;this.size = 0;}push(item) {const tail = (this.head + this.size) % this.capacity;this.buffer[tail] = item;if (this.size === this.capacity) {this.head = (this.head + 1) % this.capacity;} else {this.size++;}}toArray() {const result = new Array(this.size);for (let i = 0; i < this.size; i++) {result[i] = this.buffer[(this.head + i) % this.capacity];}return result;}}
svelte
Erklärung
1
const tail = (this.head + this.size) % this.capacity;
Berechnet den Schreibindex zirkulär per Modulo über ein fest zugewiesenes Array.
2
this.head = (this.head + 1) % this.capacity;
Rückt den Head-Offset vor sobald Kapazität erreicht ist, um älteste Einträge zu überschreiben.
3
result[i] = this.buffer[(this.head + i) % this.capacity];
Projiziert zirkulären Speicher in ein geordnetes Array für Svelte Keyed-Each-Rendering.