-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathwindows.ts
More file actions
40 lines (38 loc) · 1.08 KB
/
windows.ts
File metadata and controls
40 lines (38 loc) · 1.08 KB
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
/**
* Creates sliding windows of a specified size from an iterable.
* @example
* ```ts
* [...windows([1,2,3,4], 2)] // [[1,2], [2,3], [3,4]]
* [...windows(3)([1,2,3,4,5])] // [[1,2,3], [2,3,4], [3,4,5]]
* ```
*/
export function windows(
size: number
): <T>(iter: Iterable<T>) => IterableIterator<T[]>;
export function windows<T>(
iter: Iterable<T>,
size: number
): IterableIterator<T[]>;
export function windows<T>(
sizeOrIter: number | Iterable<T>,
maybeSize?: number
): IterableIterator<T[]> | (<T>(iter: Iterable<T>) => IterableIterator<T[]>) {
if (typeof sizeOrIter === "number") {
// Curried form: return a function that takes an iterable
return <T>(iter: Iterable<T>) => _windows(iter, sizeOrIter);
}
// Direct form: create windows from the iterable
return _windows(sizeOrIter, maybeSize!);
}
function* _windows<T>(iter: Iterable<T>, size: number): IterableIterator<T[]> {
let arr: T[] = [];
for (const item of iter) {
if (arr.length === size) {
arr = arr.slice(1);
}
arr.push(item);
if (arr.length === size) {
yield arr;
}
}
}