javascript / expert
Snippet
Double-Buffered Array Queue for Concurrent React Reducer Processing
Implements an array-based double-buffering queue pattern using ES private class fields. This architecture isolates concurrent action pushes into a write buffer while React context or reducer logic safely consumes and reduces collected state actions from a swapped read buffer.
snippet.js
javascript
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
class DoubleBufferedQueue {#readBuffer = [];#writeBuffer = [];enqueue(item) {this.#writeBuffer.push(item);}swap() {const temp = this.#readBuffer;this.#readBuffer = this.#writeBuffer;this.#writeBuffer = temp;this.#writeBuffer.length = 0;return this.#readBuffer;}process(reducerFn, initialState) {const activeItems = this.swap();return activeItems.reduce(reducerFn, initialState);}}
react
Breakdown
1
#readBuffer = []; #writeBuffer = [];
Encapsulates private internal array storage using private class fields syntax.
2
enqueue(item) { this.#writeBuffer.push(item); }
Appends incoming state updates to the isolated write buffer without touching active read data.
3
swap() { ... this.#writeBuffer.length = 0; }
Swaps buffer references instantly and clears the new write buffer using array length mutation.
4
return activeItems.reduce(reducerFn, initialState);
Folds the collected array items into a single updated state object using Array.prototype.reduce.