javascript / expert
Snippet
Memory-Efficient Array Chunk Streaming with Generators and Sliding Window Control
Evaluating large collections by copying sub-arrays into memory simultaneously causes high memory allocation overhead. Generator-based sliding windows construct windowed array slices lazily on demand, optimizing memory footprints during iterative stream processing.
snippet.js
javascript
1
2
3
4
5
6
7
8
9
10
11
export function* createSlidingWindowIterable(items, size) {if (size <= 0 || !Array.isArray(items)) return;const window = [];for (const item of items) {window.push(item);if (window.length === size) {yield [...window];window.shift();}}}
nodejs
Breakdown
1
export function* createSlidingWindowIterable(items, size) {
Declares a generator function returning an iterable sequence of window slices.
2
if (size <= 0 || !Array.isArray(items)) return;
Validates boundary arguments to prevent infinite execution loops.
3
if (window.length === size) {
Checks if the target window size has been accumulated.
4
yield [...window];
Emits a shallow copy of the current window snapshot.
5
window.shift();
Removes the oldest element to advance the sliding frame.