-
Notifications
You must be signed in to change notification settings - Fork 3
/
frame.js
46 lines (38 loc) · 1 KB
/
frame.js
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
import {iter} from './iter.js';
import {range} from './range.js';
/**
* Yields tuples that contain the current element of the input iterable and the
* next <code>n-1</code> elements of the input iterable.
*
* @example
* frame( range( 100 ) , 2 ) ;
* // is equivalent to
* zip( range( 100 ) , range( 1 , 100 ) ) ;
*
* @param {Iterable} iterable - The input iterable.
* @param {Number} n - The frame size.
* @returns {Iterator}
*
*/
export function* frame(iterable, n) {
// Could have an implementation using a deque
// that doesn't slice (and thus allocate a new
// vector everytime). Though the yield object
// could not be modified by the caller in that case.
const iterator = iter(iterable);
let tuple = [];
// eslint-disable-next-line no-unused-vars
for (const i of range(n)) {
const current = iterator.next();
if (current.done) {
return;
}
tuple.push(current.value);
}
yield tuple;
for (const value of iterator) {
tuple = tuple.slice(1);
tuple.push(value);
yield tuple;
}
}