From f644ecd26be023baf2a783e54e21a9258f3ffa11 Mon Sep 17 00:00:00 2001 From: Karsten Schmidt Date: Wed, 20 Mar 2019 17:12:31 +0000 Subject: [PATCH] fix(transducers): update mean() completion step to avoid div by zero --- packages/transducers/src/rfn/mean.ts | 10 +++++++++- 1 file changed, 9 insertions(+), 1 deletion(-) diff --git a/packages/transducers/src/rfn/mean.ts b/packages/transducers/src/rfn/mean.ts index bc29cb9d1b..cbfe9cccf2 100644 --- a/packages/transducers/src/rfn/mean.ts +++ b/packages/transducers/src/rfn/mean.ts @@ -1,11 +1,19 @@ import { Reducer } from "../api"; import { reduce } from "../reduce"; +/** + * Reducer computing mean of received inputs. Returns 0 if no inputs + * were processed. + */ export function mean(): Reducer; export function mean(xs: Iterable): number; export function mean(xs?: Iterable): any { let n = 0; return xs ? reduce(mean(), xs) - : [() => 0, (acc) => acc / n, (acc, x) => (n++, acc + x)]; + : [ + () => 0, + (acc) => (n > 1 ? acc / n : acc), + (acc, x) => (n++, acc + x) + ]; }