Skip to content

windowed() function

Returns Iterable/AsyncIterable of sliding windows of the given size over the iterable. Windows overlap: each one starts one element after the previous one. When the iterable has fewer elements than size, nothing is yielded.

Unlike chunk, which splits into non-overlapping groups, windowed yields every consecutive run of size elements.

Signature:

typescript
declare function windowed<T>(size: number, iterable: Iterable<T>): IterableIterator<T[]>;

Example

ts
const iter = windowed(2, [1, 2, 3, 4]);
iter.next(); // {done: false, value: [1, 2]}
iter.next(); // {done: false, value: [2, 3]}
iter.next(); // {done: false, value: [3, 4]}
iter.next(); // {done: true, value: undefined}

// with pipe
pipe(
  [1, 2, 3, 4, 5],
  windowed(3),
  toArray,
); // [[1, 2, 3], [2, 3, 4], [3, 4, 5]]

Open Source Code

Released under the Apache-2.0 License.