Comparing version 0.0.2 to 0.0.3
{ | ||
"name": "fiter", | ||
"version": "0.0.2", | ||
"version": "0.0.3", | ||
"description": "", | ||
@@ -5,0 +5,0 @@ "main": "./src/index.js", |
@@ -72,2 +72,11 @@ # Fiter | ||
### reduce | ||
Analagous to the `Array.prototype.reduce` method, fiter provides its own reduce that works on any sync/async iterable value. If the iterable is synchronous the value is returned synchronously. If the iterable is async a Promise of the value is returned. | ||
```javascript | ||
const file = fs.createReadStream('./somefilepath.txt'); | ||
const lines = await reduce(file, (acc, value) => acc + countNewLineCharacters(chunk), 0); | ||
``` | ||
### find | ||
@@ -74,0 +83,0 @@ |
@@ -27,2 +27,11 @@ export declare function map<T, K>(it: Iterable<T>, fn: (value: T) => K): Iterable<K>; | ||
export declare function reduce<T, K>(it: Iterable<T>, fn: (acc: T | undefined, value: T) => T): T | undefined; | ||
export declare function reduce<T, K>(it: Iterable<T>, fn: (acc: K, value: T) => K, initialAcc: K): K; | ||
export declare function reduce<T, K>(it: AsyncIterable<T>, fn: (acc: T, value: T) => T): Promise<T | undefined>; | ||
export declare function reduce<T, K>( | ||
it: AsyncIterable<T>, | ||
fn: (acc: K, value: T) => K, | ||
initialAcc: K | ||
): K extends Promise<any> ? K : Promise<K>; | ||
type Iter = Iterable<any> | AsyncIterable<any>; | ||
@@ -29,0 +38,0 @@ type IsAsyncIterResultType<T extends Iter[]> = { |
@@ -122,2 +122,37 @@ 'use strict'; | ||
function syncReduce(iter, fn, acc) { | ||
if (acc === undefined) { | ||
const { value, done } = iter.next(); | ||
if (done) { | ||
return value; | ||
} | ||
acc = value; | ||
} | ||
for (const value of iter) { | ||
acc = fn(acc, value); | ||
} | ||
return acc; | ||
} | ||
async function asyncReduce(iter, fn, acc) { | ||
if (acc === undefined) { | ||
const { value, done } = await iter.next(); | ||
if (done) { | ||
return value; | ||
} | ||
acc = value; | ||
} | ||
for await (const value of iter) { | ||
acc = fn(acc, value); | ||
} | ||
return acc; | ||
} | ||
function reduce(iter, fn, acc) { | ||
if (iter[Symbol.asyncIterator]) { | ||
return asyncReduce(iter[Symbol.asyncIterator](), fn, acc); | ||
} | ||
return syncReduce(iter[Symbol.iterator](), fn, acc); | ||
} | ||
module.exports = { | ||
@@ -129,4 +164,5 @@ map, | ||
find, | ||
reduce, | ||
flatMap, | ||
flat, | ||
}; |
10510
187
164