Aller au contenu principal

window()

window<T>(array, size): T[][]

Creates a sliding window array of consecutive elements.

Returns an array of overlapping subarrays of the specified size, each shifted by one element from the previous.

💎 Why is this a Hidden Gem?

Creates sliding windows over arrays. Instead of writing error-prone for loops with array[i] and array[i+1], get clean tuples like [[1,2,3], [2,3,4], [3,4,5]]. Perfect for moving averages, trend detection, and comparing consecutive elements.


Type Parameters

T: T

The type of elements in the array.


Parameters

array: readonly T[]

The source array to process.

size: number

The size of each window (must be a positive integer).


Returns: T[][]

An array of subarrays, each containing size consecutive elements.


Throws

RangeError When size is not a positive integer.


Since

2.0.0


Performance

O(n×m) time & space, pre-allocated array, early return when size > length.


Also known as

aperture (Ramda) · sliding (Effect) · window (es-toolkit) · ❌ (Lodash, Remeda, Radashi, Modern Dash, Antfu)


Example

window([1, 2, 3, 4, 5], 3);
// => [[1, 2, 3], [2, 3, 4], [3, 4, 5]]

How it works?

Window creates overlapping subarrays by sliding one element at a time. Unlike chunk which splits without overlap, window preserves continuity between groups.

Window vs Chunk

OperationOverlapOutput for [1,2,3,4,5] size 3
window(arr, 3)Yes[[1,2,3], [2,3,4], [3,4,5]]
chunk(arr, 3)No[[1,2,3], [4,5]]

Use Cases

Detecting changes between consecutive values 📌

Compare adjacent elements to identify transitions, changes, or deltas in sequences. Perfect for tracking state changes, price movements, or any sequential comparisons.

const temperatures = [18, 19, 22, 21, 25, 24];

const changes = window(temperatures, 2).map(([prev, curr]) => curr - prev);
// => [1, 3, -1, 4, -1]

const biggestJump = Math.max(...changes);
// => 4 (between 21 and 25)

Pairwise operations on sequences

Process elements in pairs for comparisons, validations, or transformations. Essential for route calculations, interval analysis, or sequential validations.

const waypoints = ["Paris", "Lyon", "Marseille", "Nice"];

const legs = window(waypoints, 2);
// => [["Paris", "Lyon"], ["Lyon", "Marseille"], ["Marseille", "Nice"]]

const routes = legs.map(([from, to]) => `${from}${to}`);
// => ["Paris → Lyon", "Lyon → Marseille", "Marseille → Nice"]

Moving averages for data smoothing

Calculate rolling averages to smooth out fluctuations and reveal underlying trends. Essential for financial analysis, sensor data processing, and performance monitoring.

const stockPrices = [100, 102, 98, 105, 110, 108];

const movingAvg = window(stockPrices, 3).map(
(w) => w.reduce((a, b) => a + b, 0) / w.length
);
// => [100, 101.67, 104.33, 107.67]