Skip to content

Commit

Permalink
fix: buffer can now take any iterableish
Browse files Browse the repository at this point in the history
  • Loading branch information
reconbot committed May 13, 2018
1 parent 5aa715e commit 162ce04
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 11 deletions.
19 changes: 12 additions & 7 deletions lib/buffer-test.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,7 @@
import { assert } from 'chai'
import { buffer } from '../lib/buffer'
import { buffer } from './'

if ((Symbol as any).asyncIterator === undefined) {
((Symbol as any).asyncIterator) = Symbol.for('asyncIterator')
}

function promiseImmediate (data?) {
function promiseImmediate<T> (data?: T): Promise<T> {
return new Promise(resolve => setImmediate(() => resolve(data)))
}

Expand All @@ -19,7 +15,6 @@ describe('buffer', () => {
}
const itr = buffer(5, numbers())
await promiseImmediate()
await promiseImmediate()
assert.equal(num, 0)
const { value } = await itr.next()
assert.equal(value, 1)
Expand All @@ -30,6 +25,7 @@ describe('buffer', () => {
await promiseImmediate()
assert.equal(num, 6)
})

it('buffers sync data', async () => {
let num = 0
function* numbers () {
Expand All @@ -43,4 +39,13 @@ describe('buffer', () => {
assert.equal(value, 1)
assert.equal(num, 6)
})
it('buffers sync iterables', async () => {
const itr = buffer(2, [1, 2, 3, 4, 5, 6])
assert.equal(1, (await itr.next()).value)
assert.equal(2, (await itr.next()).value)
assert.equal(3, (await itr.next()).value)
assert.equal(4, (await itr.next()).value)
assert.equal(5, (await itr.next()).value)
assert.equal(6, (await itr.next()).value)
})
})
14 changes: 10 additions & 4 deletions lib/buffer.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,11 @@
async function* _buffer (size: number, iterable: Iterator<any>) {
import { fromIterable } from './from-iterable'
import { Iterableish } from './types'

async function* _buffer<T> (size: number, iterable: Iterableish<T>): AsyncIterableIterator<T> {
const iterator = fromIterable(iterable as Iterable<T>)
const buff = []
for (let i = 0; i <= size; i++) {
buff.push(iterable.next())
buff.push(iterator.next())
}
while (true) {
const { value, end } = await buff.shift()
Expand All @@ -10,11 +14,13 @@ async function* _buffer (size: number, iterable: Iterator<any>) {
} else {
return
}
buff.push(iterable.next())
buff.push(iterator.next())
}
}

export function buffer (size: number, iterable?: Iterator<any>) {
export function buffer<T> (size: number): (iterable: Iterableish<T>) => AsyncIterableIterator<T>
export function buffer<T> (size: number, iterable: Iterableish<T>): AsyncIterableIterator<T>
export function buffer (size, iterable?) {
if (iterable === undefined) {
return curriedIterable => _buffer(size, curriedIterable)
}
Expand Down

0 comments on commit 162ce04

Please sign in to comment.