-
Notifications
You must be signed in to change notification settings - Fork 3
/
slice.js
47 lines (37 loc) · 840 Bytes
/
slice.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
47
import {iter} from '../index.js';
/**
* Same as
* <code>map( [ i , x ] => x , filter( [ i , x ] => (new Set( range( start ,
* stop , step ) ) ).has( i ) , enumerate( iterable ) ) );</code>.
*
* @param {Iterable} iterable - The input iterable.
* @param {Number} start - Where to start the slice.
* @param {Number} stop - Where to stop the slice.
* @param {Number} step - The step of the slice.
* @returns {Iterator}
*/
export function* slice(iterable, start, stop, step) {
const iterator = iter(iterable);
while (start > 0) {
if (iterator.next().done) {
return;
}
--start;
--stop;
}
while (stop > 0) {
const current = iterator.next();
if (current.done) {
return;
}
yield current.value;
--stop;
let n = step;
while (n > 1) {
if (iterator.next().done) {
return;
}
--n;
}
}
}