Skip to content

Commit 0d059ab

Browse files
committed
feat(average): add average function
1 parent 3fd828b commit 0d059ab

File tree

2 files changed

+18
-0
lines changed

2 files changed

+18
-0
lines changed

index.test.ts

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
import test from "ava";
22
import {
33
asyncIterable,
4+
average,
45
contains,
56
drop,
67
dropWhile,
@@ -263,3 +264,9 @@ test("product", async t => {
263264
t.is(await product(asyncIterable([1, 2, 3, 2])), 12);
264265
t.is(await product(asyncIterable([])), 1);
265266
});
267+
268+
test("average", async t => {
269+
t.is(await average(asyncIterable([1, 2, 3])), 2);
270+
t.is(await average(asyncIterable([1, 2, 3, 2])), 2);
271+
t.is(await average(asyncIterable([])), null);
272+
});

index.ts

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -836,3 +836,14 @@ export async function product(iterable: AsyncIterableLike<number>): Promise<numb
836836
}
837837

838838
export const asyncProduct = product;
839+
840+
export async function average(iterable: AsyncIterableLike<number>): Promise<number | null> {
841+
const [sum, count] = await fold(
842+
iterable,
843+
([sum], element, index) => [sum + element, index + 1],
844+
[0, 0]
845+
);
846+
return count === 0 ? null : sum / count;
847+
}
848+
849+
export const asyncAverage = average;

0 commit comments

Comments
 (0)