From 4a553e3cbb1396716127395dc720723d2762485c Mon Sep 17 00:00:00 2001 From: Richard Ramos Date: Wed, 21 Aug 2019 08:44:07 -0400 Subject: [PATCH] improve average operator --- src/operators.js | 29 ++++++++++++++++++++--------- 1 file changed, 20 insertions(+), 9 deletions(-) diff --git a/src/operators.js b/src/operators.js index eacd559..d60be61 100644 --- a/src/operators.js +++ b/src/operators.js @@ -21,15 +21,26 @@ of({a: 1, b:2, e: 1}, {a: 0, c: 1, b:3}, {a: 0, d: 1, b:1}) .subscribe((v) => console.log(v)); */ -function $average() { - return pipe( - reduce((accum, curr) => ({ - sum: accum.sum + curr, - count: accum.count + 1 - }), { sum: 0, count: 0 }), - map(o => o.sum / o.count) - ); -} +function $average(cb) { + return pipe( + reduce((accum, curr) => { + let currentValue; + if (typeof cb === 'string' || cb instanceof String){ + currentValue = curr[cb]; + } else if(typeof cb === "function") { + currentValue = cb(curr); + } else { + currentValue = curr; + } + + return { + sum: accum.sum + currentValue, + count: accum.count + 1 + } + }, { sum: 0, count: 0 }), + map(o => o.sum / o.count) + ); + } /* of(10, 3, 4)