简体   繁体   English

nodejs:计算高地流的均值

[英]nodejs: calculate mean with highland streams

I am just getting started with highland.js and streams in node and I am stuck trying to calculate the min/max/mean of some numbers. 我刚开始使用highland.js和node中的流,但是我一直试图计算某些数字的最小值/最大值/平均值。 This is what I have so far: 这是我到目前为止的内容:

const _ = require('highland');

const input = [
 { val: 1 },
 { val: 2 },
 { val: 3 },
];

_(input)
  .reduce((acc, { val }) => {
    if (typeof acc.min === 'undefined' || val < acc.min) {
      acc.min = val;
    }
    if (typeof acc.max === 'undefined' || val > acc.max) {
      acc.max = val;
    }
    acc.count = (acc.count || 0) + 1;
    acc.sum = (acc.sum || 0) + val;
    return acc;
  }, {});

If I then do, say, toCallback and console.log the result I get {min: 1, max: 3, count: 3, sum: 6} but I am not interested in the count and sum fields, I want the object like {min: 1, max: 3, mean: 2} . 如果然后我做toCallbackconsole.log的结果,我得到{min: 1, max: 3, count: 3, sum: 6}但是我对count和sum字段不感兴趣,我希望对象像{min: 1, max: 3, mean: 2}

However, since the return of the reduce is an object, there's nothing highland can do with it - I can only consume it but I would like to do the average in highland land. 但是,由于reduce的返回是一个对象,因此高原没有任何用途-我只能消耗它,但我想在高原上进行平均。

How can I continue from here or how should I refactor the code to get that average? 我如何从这里继续,或者应该如何重构代码以获得该平均值?

You could try using highland .map method like this: 您可以尝试使用highland .map方法,如下所示:

 _(input) .reduce({}, (acc, {val}) => { if (typeof acc.min === 'undefined' || val < acc.min) { acc.min = val; } if (typeof acc.max === 'undefined' || val > acc.max) { acc.max = val; } acc.count = (acc.count || 0) + 1; acc.sum = (acc.sum || 0) + val; return acc; }) .map(stats => { return { min: stats.min, max: stats.max, mean: stats.sum / stats.count }; }) .toCallback(function (err, data) { //Contains the data structure you need console.log(data); }); 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM