Skip to content

Commit

Permalink
Fix logic bug in take() that @vidartf noticed
Browse files Browse the repository at this point in the history
  • Loading branch information
afshin committed Aug 16, 2022
1 parent da91b28 commit c6673e8
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 8 deletions.
11 changes: 7 additions & 4 deletions packages/algorithm/src/take.ts
Original file line number Diff line number Diff line change
Expand Up @@ -35,9 +35,12 @@ export function* take<T>(
object: Iterable<T>,
count: number
): IterableIterator<T> {
for (const value of object) {
if (0 < count--) {
yield value;
}
if (count < 1) {
return;
}
const it = object[Symbol.iterator]();
let item: IteratorResult<T>;
while (0 < count-- && !(item = it.next()).done) {
yield item.value;
}
}
13 changes: 9 additions & 4 deletions packages/algorithm/tests/src/take.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,13 +20,18 @@ describe('@lumino/algorithm', () => {

describe('take() from an iterable iterator', () => {
testIterator(() => {
return [take([0, 1, 2, 3][Symbol.iterator](), 1), [0]];
return [take([0, 1, 2, 3], 1), [0]];
});
});

describe('take() with count=0', () => {
testIterator(() => {
return [take([0, 1, 2, 3][Symbol.iterator](), 0), []];
});
testIterator(() => [take([0, 1, 2, 3], 0), []]);
});

describe('take() only takes as many as count or are left', () => {
const it = [0, 1, 2, 3, 4, 5, 6][Symbol.iterator]();
testIterator(() => [take(it, 2), [0, 1]]);
testIterator(() => [take(it, 4), [2, 3, 4, 5]]);
testIterator(() => [take(it, 25), [6]]);
});
});

0 comments on commit c6673e8

Please sign in to comment.