/
sliding_windows.ts
76 lines (73 loc) · 2.13 KB
/
sliding_windows.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
// Copyright 2018-2022 the Deno authors. All rights reserved. MIT license.
// This module is browser compatible.
/**
* Generates sliding views of the given array of the given size and returns a new
* 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.
* (Default: false)
*
* Example:
*
* ```ts
* import { slidingWindows } from "https://deno.land/std@$STD_VERSION/collections/mod.ts";
* import { assertEquals } from "https://deno.land/std@$STD_VERSION/testing/asserts.ts";
* 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],
* ]);
* ```
*/
export function slidingWindows<T>(
array: readonly T[],
size: number,
{ step = 1, partial = false }: {
/**
* If step is set, each window will start that many elements after the last
* window's start. (Default: 1)
*/
step?: number;
/**
* 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.
* (Default: false)
*/
partial?: boolean;
} = {},
): T[][] {
if (
!Number.isInteger(size) || !Number.isInteger(step) || size <= 0 || step <= 0
) {
throw new RangeError("Both size and step must be positive integer.");
}
/** length of the return array */
const length = Math.floor((array.length - (partial ? 1 : size)) / step + 1);
const result = [];
for (let i = 0; i < length; i++) {
result.push(array.slice(i * step, i * step + size));
}
return result;
}