javascript / expert
Snippet
Circular Buffer Pipeline Management using In-Place Array Mutations in Svelte Subscriptions
Implements a fixed-capacity ring buffer using index math over pre-allocated array storage. It emits ordered snapshot arrays to Svelte subscribers, preventing garbage collection thrashing during telemetry streams.
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
import { writable } from 'svelte/store';export function createCircularBufferStore(capacity) {const buffer = new Array(capacity).fill(null);let head = 0;let count = 0;const store = writable([]);return {subscribe: store.subscribe,push(item) {buffer[head] = item;head = (head + 1) % capacity;if (count < capacity) count++;const ordered = new Array(count);for (let i = 0; i < count; i++) {ordered[i] = buffer[(head - count + i + capacity) % capacity];}store.set(ordered);}};}
svelte
Breakdown
1
const buffer = new Array(capacity).fill(null);
Pre-allocates a fixed-size contiguous backing array to eliminate heap dynamic re-allocation.
2
head = (head + 1) % capacity;
Calculates write offset wrapped around array bounds via modulo arithmetic.
3
ordered[i] = buffer[(head - count + i + capacity) % capacity];
Reconstructs chronological element order from circular array index relative to write head.