slidingWindows
import { slidingWindows } from "jsr:@ende/collections";function
function slidingWindows<T>(iterable: Iterable<T>, size: number, options: SlidingWindowsOptions = [UNSUPPORTED]): T[][]Generates sliding views of the given iterable of the given size and returns an array containing all of them.
If step is set, each window will start that many elements after the last window's start. (Default: 1)
If partial is set, windows will be generated for the last elements of the collection, resulting in some undefined values if size is greater than 1.
iterable: Iterable<T>The iterable to generate sliding windows from.
size: numberThe size of the sliding windows.
options: SlidingWindowsOptions = [UNSUPPORTED]The options for generating sliding windows.
Returns
An array containing all sliding windows of the given size.
Example: Usage
import { slidingWindows } from "@ende/collections/sliding-windows";
import { assertEquals } from "@ende/assert";
const numbers = [1, 2, 3, 4, 5];
const windows = slidingWindows(numbers, 3);
assertEquals(windows, [
[1, 2, 3],
[2, 3, 4],
[3, 4, 5],
]);
const windowsWithStep = slidingWindows(numbers, 3, { step: 2 });
assertEquals(windowsWithStep, [
[1, 2, 3],
[3, 4, 5],
]);
const windowsWithPartial = slidingWindows(numbers, 3, { partial: true });
assertEquals(windowsWithPartial, [
[1, 2, 3],
[2, 3, 4],
[3, 4, 5],
[4, 5],
[5],
]);