-
Notifications
You must be signed in to change notification settings - Fork 4
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
feat: Take now can return a sync iterator
Bonus: removed the example from the readme, wasn’t better than our api examples
- Loading branch information
Showing
3 changed files
with
38 additions
and
61 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,20 +1,41 @@ | ||
import { AnyIterable } from './types' | ||
|
||
async function* _take<T>(count: number, iterable: AnyIterable<T>) { | ||
async function* _take<T>(count: number, iterable: AsyncIterable<T>) { | ||
let taken = 0 | ||
for await (const val of iterable as AsyncIterable<T>) { | ||
for await (const val of iterable) { | ||
yield await val | ||
taken++ | ||
if (taken >= count) { | ||
return | ||
} | ||
} | ||
} | ||
export function take<T>(count: number): (iterable: AnyIterable<T>) => AsyncIterableIterator<T> | ||
export function take<T>(count: number, iterable: AnyIterable<T>): AsyncIterableIterator<T> | ||
export function take(count, iterable?) { | ||
|
||
function* _syncTake<T>(count: number, iterable: Iterable<T>) { | ||
let taken = 0 | ||
for (const val of iterable) { | ||
yield val | ||
taken++ | ||
if (taken >= count) { | ||
return | ||
} | ||
} | ||
} | ||
|
||
export function take<T>( | ||
count: number | ||
): { | ||
(curriedIterable: AsyncIterable<T>): AsyncIterableIterator<T> | ||
(curriedIterable: Iterable<T>): IterableIterator<T> | ||
} | ||
export function take<T>(count: number, iterable: AsyncIterable<T>): AsyncIterableIterator<T> | ||
export function take<T>(count: number, iterable: Iterable<T>): IterableIterator<T> | ||
export function take<T>(count: number, iterable?: AnyIterable<T>) { | ||
if (iterable === undefined) { | ||
return curriedIterable => _take(count, curriedIterable) | ||
return curriedIterable => take(count, curriedIterable) | ||
} | ||
if (iterable[Symbol.asyncIterator]) { | ||
return _take(count, iterable as AsyncIterable<T>) | ||
} | ||
return _take(count, iterable) | ||
return _syncTake(count, iterable as Iterable<T>) | ||
} |