Js计算平均值的不同实现方式

更新日期: 2019-06-18 阅读: 2.4k 标签: 运算

本文翻译并严重删减自five-ways-to-average-with-js-reduce/

如果我们有以下数组:需求是先过滤掉 found 为 false 的 item 再计算求平均值

const victorianSlang = [
  {
    term: "doing the bear",
    found: true,
    popularity: 108
  },
  {
    term: "katterzem",
    found: false,
    popularity: null
  },
  {
    term: "bone shaker",
    found: true,
    popularity: 609
  },
  {
    term: "smothering a parrot",
    found: false,
    popularity: null
  }
  //……
];


一般想到的方法不外乎是一下几种:

1、for 循环 (可阅读性差,写法并不优雅)

let popularitySum = 0;
let itemsFound = 0;
const len = victorianSlang.length;
let item = null;
for (let i = 0; i < len; i++) {
  item = victorianSlang[i];
  if (item.found) {
    popularitySum = item.popularity + popularitySum;
    itemsFound = itemsFound + 1;
  }
}
const averagePopularity = popularitySum / itemsFound;
console.log("Average popularity:", averagePopularity);


2、 使用 filter/map/reduce 分离功能(代码非常干净,实际开发我们更多可能用的是这种方式)

// Helper functions
// ----------------------------------------------------------------------------
function isFound(item) {
  return item.found;
}

function getPopularity(item) {
  return item.popularity;
}

function addScores(runningTotal, popularity) {
  return runningTotal + popularity;
}

// Calculations
// ----------------------------------------------------------------------------

// Filter out terms that weren't found in books.
const foundSlangTerms = victorianSlang.filter(isFound);

// Extract the popularity scores so we just have an array of numbers.
const popularityScores = foundSlangTerms.map(getPopularity);

// Add up all the scores total. Note that the second parameter tells reduce
// to start the total at zero.
const scoresTotal = popularityScores.reduce(addScores, 0);

// Calculate the average and display.
const averagePopularity = scoresTotal / popularityScores.length;
console.log("Average popularity:", averagePopularity);


3、 使用串联的方式。第二种方式并没有什么问题,只是多了两个中间变量,在可阅读性上我还是更倾向于它。但基于Fluent interface原则(https://en.wikipedia.org/wiki...,我们可以简单改一下函数

// Helper functions
// ---------------------------------------------------------------------------------
function isFound(item) {
  return item.found;
}

function getPopularity(item) {
  return item.popularity;
}

// We use an object to keep track of multiple values in a single return value.
function addScores({ totalPopularity, itemCount }, popularity) {
  return {
    totalPopularity: totalPopularity + popularity,
    itemCount: itemCount + 1
  };
}

// Calculations
// ---------------------------------------------------------------------------------
const initialInfo = { totalPopularity: 0, itemCount: 0 };
const popularityInfo = victorianSlang
  .filter(isFound)
  .map(getPopularity)
  .reduce(addScores, initialInfo);
const { totalPopularity, itemCount } = popularityInfo;
const averagePopularity = totalPopularity / itemCount;
console.log("Average popularity:", averagePopularity);


4、函数编程式。前面三种相信在工作中是很常用到的,这一种方式熟悉 react 的同学肯定不陌生,我们会根据 api 去使用 compose。如果我们给自己设限,要求模仿这种写法去实现呢?强调下在实际开发中可能并没有什么意义,只是说明了 js 的实现不止一种。

// Helpers
// ----------------------------------------------------------------------------
const filter = p => a => a.filter(p);
const map = f => a => a.map(f);
const prop = k => x => x[k];
const reduce = r => i => a => a.reduce(r, i);
const compose = (...fns) => arg => fns.reduceRight((arg, fn) => fn(arg), arg);

// The blackbird combinator.
// See: https://jrsinclair.com/articles/2019/compose-js-functions-multiple-parameters/
const B1 = f => g => h => x => f(g(x))(h(x));

// Calculations
// ----------------------------------------------------------------------------

// We'll create a sum function that adds all the items of an array together.
const sum = reduce((a, i) => a + i)(0);

// A function to get the length of an array.
const length = a => a.length;

// A function to divide one number by another.
const div = a => b => a / b;

// We use compose() to piece our function together using the small helpers.
// With compose() you read from the bottom up.
const calcPopularity = compose(
  B1(div)(sum)(length),
  map(prop("popularity")),
  filter(prop("found"))
);

const averagePopularity = calcPopularity(victorianSlang);
console.log("Average popularity:", averagePopularity);


5、只有一次遍历的情况。上面几种方法实际上都用了三次遍历。如果有一种方法能够只遍历一次呢?需要了解一点数学知识如下图,总之就是经过一系列的公式转换可以实现一次遍历。

clipboard.png

// Average function
// ----------------------------------------------------------------------------

function averageScores({ avg, n }, slangTermInfo) {
  if (!slangTermInfo.found) {
    return { avg, n };
  }
  return {
    avg: (slangTermInfo.popularity + n * avg) / (n + 1),
    n: n + 1
  };
}

// Calculations
// ----------------------------------------------------------------------------

// Calculate the average and display.
const initialVals = { avg: 0, n: 0 };
const averagePopularity = victorianSlang.reduce(averageScores, initialVals).avg;
console.log("Average popularity:", averagePopularity);

总结:数学学得好,代码写得少


本文翻译并严重删减自five-ways-to-average-with-js-reduce/ 

翻译来源:https://segmentfault.com/a/1190000019516191

 

本文内容仅供个人学习、研究或参考使用,不构成任何形式的决策建议、专业指导或法律依据。未经授权,禁止任何单位或个人以商业售卖、虚假宣传、侵权传播等非学习研究目的使用本文内容。如需分享或转载,请保留原文来源信息,不得篡改、删减内容或侵犯相关权益。感谢您的理解与支持!

链接: https://fly63.com/article/detial/3767

相关推荐

Js es6中扩展运算符(...)

拓展运算符,是es6一个很好的特性,它们可以通过减少赋值语句的使用,或者减少通过下标访问数组或对象的方式,使代码更加简洁优雅,可读性更佳。下面我将列出拓展运算符的主要应用场景,以及相关知识。

js除了Math.floor方法,还可以通过位运算|,>>实现向下取整

我们都知道通过Math.floor()方法可实现数值的向下取整,得到小于或等于该数字的最大整数。除了Math.floor方法,还可以使用位运算|,>>来实现向下取整哦

JS中三个点(...)

我们在看js代码时经常会出现(...)三个点的东西,它究竟是什么意思?又有何用处?下面我就给大家分享一下三个点的那些事

js各种取整方式及方法_四舍五入、向上取整、向下取整

js实现:四舍五入、向上取整、向下取整等方法。parseInt、Math.ceil、Math.round、Math.floor、toFixed等的使用

js取反运算

取反运算形式上是一个感叹号,用于将布尔值变为相反值,即true变成false,false变成true。不管X是什么类型的值,经过两次取反运算后,变成了与Boolean函数结果相同的布尔值。所以,两次取反就是将一个值转成布尔值的简便写法。

js中使用位运算,让执行效率更高

平常的数值运算,其本质都是先转换成二进制再进行运算的,而位运算是直接进行二进制运算,所以原则上位运算的执行效率是比较高的,由于位运算的博大精深,下面通过一些在js中使用位运算的实例

js 检验四则运算字符串是否合法

是可以通过检验的,并且在js中也是按数学表达式计算结果的, 但是这个算不算“合格”的数学表达式呢?这个就看具体情况了吧,要规避也比较简单

JS怎样做四舍五入?

toFixed() 方法可把 Number 四舍五入为指定小数位数的数字。例如将数据Num保留2位小数,则表示为:toFixed(Num);但是其四舍五入的规则与数学中的规则不同,使用的是银行家舍入规则

巧用JS位运算

位运算的方法在其它语言也是一样的,不局限于JS,所以本文提到的位运算也适用于其它语言。位运算是低级的运算操作,所以速度往往也是最快的

JavaScript 中的相等操作符 ( 详解 [] == []、[] == ![]、{} == !{} )

ECMAScript 中的相等操作符由两个等于号 ( == ) 表示,如果两个操作数相等,则返回 true。相等操作符会先转换操作数(通常称为强制转型),然后比较它们的相等性。

点击更多...

内容以共享、参考、研究为目的,不存在任何商业目的。其版权属原作者所有,如有侵权或违规,请与小编联系!情况属实本人将予以删除!