Skip to content

Commit ec0c207

Browse files
fix handling of infinite generators by tail
1 parent 3d0704c commit ec0c207

File tree

3 files changed

+19
-7
lines changed

3 files changed

+19
-7
lines changed

src/base/frame.js

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -19,8 +19,8 @@ export function* frame ( iterable , n ) {
1919

2020
// Could have an implementation using a deque
2121
// that doesn't slice (and thus allocate a new
22-
// vector everytime). Though the yieded object
23-
// cannot be modified by the caller in this case.
22+
// vector everytime). Though the yield object
23+
// could not be modified by the caller in that case.
2424

2525
const iterator = iter( iterable ) ;
2626

src/base/tail.js

Lines changed: 10 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -14,9 +14,12 @@ import { drop } from './drop' ;
1414
* @param {Number} n - The number of elements to include in the output.
1515
* @returns {Array} - The last <code>n</code> elements of the input iterable.
1616
*/
17-
export function tail ( iterable , n ) {
17+
export function* tail ( iterable , n ) {
1818

19-
if ( n < 0 ) return drop( iterable , -n ) ;
19+
if ( n < 0 ) {
20+
yield* drop( iterable , -n ) ;
21+
return ;
22+
}
2023

2124
const iterator = iter( iterable ) ;
2225

@@ -25,7 +28,10 @@ export function tail ( iterable , n ) {
2528

2629
while ( n --> 0 ) {
2730
const e = iterator.next( ) ;
28-
if ( e.done ) return buffer ;
31+
if ( e.done ) {
32+
yield* buffer ;
33+
return ;
34+
}
2935
buffer.push( e.value ) ;
3036
}
3137

@@ -34,6 +40,6 @@ export function tail ( iterable , n ) {
3440
buffer.shift() ;
3541
}
3642

37-
return buffer ;
43+
yield* buffer ;
3844

3945
}

test/src/base/tail.js

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
import test from 'ava' ;
22

3-
import { range , tail , list } from '../../..' ;
3+
import { range , tail , list , count } from '../../..' ;
44

55
test( "tail" , t => {
66

@@ -11,3 +11,9 @@ test( "tail" , t => {
1111
t.deepEqual( list( tail( range( 100 ) , 1000 ) ) , list( range( 100 ) ) ) ;
1212

1313
} ) ;
14+
15+
test( "construct tail of infinite generator" , t => {
16+
17+
tail( count( ) , 10 ) ;
18+
19+
} ) ;

0 commit comments

Comments
 (0)