Skip to content

Commit

Permalink
feat: Take(count: number, iterator?: iterableish)
Browse files Browse the repository at this point in the history
  • Loading branch information
reconbot committed May 13, 2018
1 parent 87665b2 commit 5aa715e
Show file tree
Hide file tree
Showing 2 changed files with 60 additions and 7 deletions.
45 changes: 45 additions & 0 deletions lib/take-test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
import { assert } from 'chai'
import { fromIterable } from '../lib/from-iterable'
import { take } from './'

async function asyncString (str) {
return String(str)
}

async function* asyncNumbers () {
yield 1
yield 2
yield 3
}

describe.only('take', () => {
it('Returns the first n elements of the given async iterable', async () => {
const values = []
for await (const val of take(2, asyncNumbers())) {
values.push(val)
}
assert.deepEqual(values, [1, 2])
})
it('Returns the first n elements of the given sync iterable', async () => {
const values = []
for await (const val of take(2, [1, 2, 3])) {
values.push(val)
}
assert.deepEqual(values, [1, 2])
})
it('lets you ask for more', async () => {
const values = []
for await (const val of take(99, [1, 2, 3])) {
values.push(val)
}
assert.deepEqual(values, [1, 2, 3])
})
it('lets you curry the count', async () => {
const values = []
const take1 = take(1)
for await (const val of take1([1, 2, 3])) {
values.push(val)
}
assert.deepEqual(values, [1])
})
})
22 changes: 15 additions & 7 deletions lib/take.ts
Original file line number Diff line number Diff line change
@@ -1,12 +1,20 @@
async function* _map (func, iterable) {
for await (const val of iterable) {
yield await func(val)
import { Iterableish } from './types'

async function* _take<T> (count: number, iterable: Iterableish<T>) {
let taken = 0
for await (const val of iterable as AsyncIterable<T>) {
yield await val
taken ++
if (taken >= count) {
return
}
}
}

export function map (func: (data: any) => any, iterable?: Iterable<any>|Iterator<any>) {
export function take<T> (count: number): (iterable: Iterableish<T>) => AsyncIterableIterator<T>
export function take<T> (count: number, iterable: Iterableish<T>): AsyncIterableIterator<T>
export function take (count, iterable?) {
if (iterable === undefined) {
return curriedIterable => _map(func, curriedIterable)
return curriedIterable => _take(count, curriedIterable)
}
return _map(func, iterable)
return _take(count, iterable)
}

0 comments on commit 5aa715e

Please sign in to comment.