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 ab4ec58
Show file tree
Hide file tree
Showing 2 changed files with 15 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;
}
}
12 changes: 8 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,17 @@ 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', () => {
const it = [0, 1, 2, 3][Symbol.iterator]();
testIterator(() => [take(it, 2), [0, 1]]);
testIterator(() => [take(it, 4), [2, 3]]);
});
});

0 comments on commit ab4ec58

Please sign in to comment.