🪟 Slides a fixed-size window over an array, one element at a time.

Info

Unlike chunk, which cuts an array into separate pieces, these windows overlap — every element but the ends appears in several of them.

Syntax

TypeScript
import { slidingWindows } from '@opentf/std';

slidingWindows<T>(arr: T[], size?: number): T[][];

Parameters

NameTypeDefaultDescription
arrT[][]The source array.
sizenumber1The length of each window.

Throws unless size is an integer greater than zero.

Returns

The windows, in order. Only whole windows are returned, so an array shorter than the window yields [] rather than a partial result. For an input of length n you get max(0, n - size + 1) windows.

Examples

TypeScript
slidingWindows([1, 2, 3, 4], 2)    //=> [[1, 2], [2, 3], [3, 4]]
slidingWindows([1, 2, 3, 4, 5], 3) //=> [[1, 2, 3], [2, 3, 4], [3, 4, 5]]

slidingWindows([1, 2], 3) //=> []  (too short for a whole window)

A moving average:

TypeScript
slidingWindows(readings, 3).map((w) => mean(w));

Deltas between neighbours:

TypeScript
slidingWindows([10, 13, 12, 20], 2).map(([a, b]) => b - a); //=> [3, -1, 8]

Compared with chunk:

TypeScript
chunk([1, 2, 3, 4], 2);          //=> [[1, 2], [3, 4]]        ← no overlap
slidingWindows([1, 2, 3, 4], 2); //=> [[1, 2], [2, 3], [3, 4]] ← overlapping
Last updated on
Edit this page