Skip to content

Commit

Permalink
feat: reduce(func, memo, iterablish)
Browse files Browse the repository at this point in the history
  • Loading branch information
reconbot committed May 13, 2018
1 parent 1197477 commit 43de718
Show file tree
Hide file tree
Showing 2 changed files with 57 additions and 1 deletion.
37 changes: 37 additions & 0 deletions lib/reduce-test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
import { assert } from 'chai'
import { collect, reduce } from './'

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

function* numbers () {
yield 1
yield 2
yield 3
}

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

const add = (num1, num2) => num1 + num2

describe('reduce', () => {
it('reduces sync functions with sync iterators', async () => {
assert.equal(await reduce(add, 0, numbers()), 6)
})
it('reduces async functions with async iterators', async () => {
assert.equal(await reduce(add, 0, asyncNumbers()), 6)
})
it('reduces async functions with iterables', async () => {
assert.equal(await reduce(add, 0, [1, 2, 3]), 6)
})
it('curryable', async () => {
const addAble = reduce(add)
const addZero = addAble(0)
assert.equal(await addZero([1, 2, 3]), 6)
})
})
21 changes: 20 additions & 1 deletion lib/reduce.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,22 @@
export function reduce () {
import { fromIterable } from '.'
import { Iterableish } from './types'
export async function _reduce<T, B> (func: (B, T) => B, start: B, iterable: Iterableish<T>) {
let value = start
for await (const nextItem of fromIterable(iterable)) {
value = await func(value, nextItem)
}
return value
}

export function reduce<T, B> (func: (B, T) => B): (start: B) => (iterable: Iterableish<T>) => Promise<B>
export function reduce<T, B> (func: (B, T) => B, start: B): (iterable: Iterableish<T>) => Promise<B>
export function reduce<T, B> (func: (B, T) => B, start: B, iterable: Iterableish<T>): Promise<B>
export function reduce (func, start?, iterable?) {
if (start === undefined) {
return (curriedStart, curriedIterable?) => reduce(func, curriedStart, curriedIterable)
}
if (iterable === undefined) {
return curriedIterable => reduce(func, start, curriedIterable)
}
return _reduce(func, start, iterable)
}

0 comments on commit 43de718

Please sign in to comment.