大神是怎樣用函數式JavaScript計算數組平均值的


譯者按: 有時候一個算法的直觀、簡潔、高效是需要作出取舍的。

本文采用意譯,版權歸原作者所有

函數式編程中用於操作數組的方法就像“毒品”一樣,它讓很多人愛上函數式編程。因為它們真的十分常用而且又超級簡單。 .map().filter()都僅需一個參數,該參數定義操作數組每一個元素的函數即可。reduce()會復雜一些,我之前寫過一篇文章介紹為什么人們難以掌握reduce()方法,其中一個原因在於很多入門資料都僅僅用算術作為例子。我寫了很多用reduce()來做算術以外的例子。

reduce()來計算數組的平均值是一個常用的模式。代碼看起來非常簡單,不過在計算最終結果之前你需要做兩個准備工作:

  • 數組的長度
  • 數組所有元素之和

這兩個事情看起來都很簡單,那么計算數組的平均值並不是很難了吧。解法如下:

function average(nums) {
    return nums.reduce((a, b) => a + b) / nums.length;
}

確實不是很難,是吧?但是如果數據結構變得復雜了,就沒那么簡單了。比如,數組里面的元素是對象,你需要先過濾掉某些對象,然后從對象中取出數字。這樣的場景讓計算平均值變得復雜了一點。

接下來我們處理一個類似的問題(從this Free Code Camp challenge獲得靈感),我們會提供 5 種不同的解法,每一種方法有各自的優點和缺點。這 5 種方法也展示了 JavaScript 的靈活。我希望可以給你在使用reduce的實戰中一些靈感。

問題提出

假設我們有一個數組,記錄了維多利亞時代常用的口語。接下來我們要找出那些依然現存於 Google Books 中的詞匯,並計算他們的平均流行度。數據的格式是這樣的:

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
    },
    {
        term: "damfino",
        found: true,
        popularity: 232
    },
    {
        term: "rain napper",
        found: false,
        popularity: null
    },
    {
        term: "donkey’s breakfast",
        found: true,
        popularity: 787
    },
    {
        term: "rational costume",
        found: true,
        popularity: 513
    },
    {
        term: "mind the grease",
        found: true,
        popularity: 154
    }
];

接下來我們用 5 中不同的方法計算平均流行度值。

1. for 循環

初次嘗試,我們不使用reduce()。如果你對數組的常用函數不熟悉,用 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);

如果你熟悉 JavaScript,上面的代碼理解起來應該很容易:

  1. 初始化polularitySumitemsFound變量。popularitySum記錄總的流行度值,itemsFound記錄我們已經找到的所有的條目;
  2. 初始化lenitem來幫助我們遍歷數組;
  3. for 循環每一次增加i的值,直到循環n次;
  4. 在循環中,我們每次取出當前索引位置的條目vitorianSlang[i]
  5. 檢查該條目是否在 Google Books 中
  6. 如果在,獲取popularity並累加到popularitySum
  7. 並遞增itemsFound
  8. 最后,用popularitySum除以itemsFound來計算平均值。

代碼雖然不是那么簡潔,但是順利完成了任務。使用數組迭代方法可以更加簡潔,接下來開始吧…..

2. 簡單模式: filter, map 和 sum

我們首先將這個問題拆分成幾個子問題:

  1. 使用fitler()找到那些在 Google Books 中的條目;
  2. 使用map()獲取流行度;
  3. 使用reuduce()來計算總的流行度;
  4. 計算平均值。

下面是實現代碼:

// 輔助函數
// ----------------------------------------------------------------------------
function isFound(item) {
    return item.found;
}

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

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

// 計算
// ----------------------------------------------------------------------------

// 找出所有isFound為true的條目
const foundSlangTerms = victorianSlang.filter(isFound);

// 從條目中獲取流行度值,返回為數組
const popularityScores = foundSlangTerms.map(getPopularity);

// 求和
const scoresTotal = popularityScores.reduce(addScores, 0);

// 計算平均值
const averagePopularity = scoresTotal / popularityScores.length;
console.log("Average popularity:", averagePopularity);

注意看addScores函數以及調用reduce()函數的那一行。addScores()接收兩個參數,第一個runningTotal,我們把它叫做累加數,它一直記錄着累加的總數。每訪問數組中的一個條目,我們都會用addScores函數來更新它的值。第二個參數popularity是當前某個元素的值。注意,第一次調用的時候,我們還沒有runningTotal的值,所以在調用reduce()的時候,我們給runningTotal初始化。也就是reduce()的第二個參數。

這個版本的代碼簡潔很多了,也更加的直觀。我們不再告訴 JavaScript 引擎如何循環,如何對當前索引的值做操作。我們定義了很多小的輔助函數,並且把它們組合起來完成任務。filter()map()reduce()幫我們做了很多工作。上面的實現更加直觀地告訴我們這段代碼要做什么,而不是底層如何去實現。

3. 簡單模式 II: 記錄多個累加值

在之前的版本中,我們創建了很多中間變量:foundSlangTermspopularityScores。接下來,我們給自己設一個挑戰,使用鏈式操作,將所有的函數調用組合起來,不再使用中間變量。注意:popularityScores.length變量需要用其它的方式來獲取。我們可以在addScores的累加參數中記錄它。

// 輔助函數
// ---------------------------------------------------------------------------------
function isFound(item) {
    return item.found;
}

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

// 我們使用一個對象來記錄總的流行度和條目的總數
function addScores({ totalPopularity, itemCount }, popularity) {
    return {
        totalPopularity: totalPopularity + popularity,
        itemCount: itemCount + 1
    };
}

// 計算
// ---------------------------------------------------------------------------------

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);

我們在reduce函數中使用對象來記錄了totalPopularityitemCount。在addScores中,每次都更新itemCount的計數。

通過filtermapreduce計算的最終的結果存儲在popularityInfo中。你甚至可以繼續簡化上述代碼,移除不必要的中間變量,讓最終的計算代碼只有一行。

4. point-free 式函數組合

注意: 如果你不熟悉函數式語言或則覺得難以理解,請跳過這部分!

如果你熟悉curry()compose(),接下來的內容就不難理解。如果你想知道更多,可以看看這篇文章: ‘A Gentle Introduction to Functional JavaScript’. 特別是第三部分

我們可以使用compose函數來構建一個完全不帶任何變量的代碼,這就叫做point-free的方式。不過,我們需要一些幫助函數。

// 輔助函數
// ----------------------------------------------------------------------------
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));

// 計算
// ----------------------------------------------------------------------------

// 求和函數
const sum = reduce((a, i) => a + i)(0);

// 計算數組長度的函數
const length = a => a.length;

// 除法函數
const div = a => b => a / b;

// 我們使用compose()來將函數組合起來
// compose()的參數你可以倒着讀,來理解程序的含義
const calcPopularity = compose(
    B1(div)(sum)(length),
    map(prop("popularity")),
    filter(prop("found"))
);

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

我們在compose中做了所有的計算。從后往前看,首先filter(prop('found'))篩選出所有在 Google Books 中的條目,然后通過map(prop('popularity'))獲取所有的流行度數值,最后使用 magical blackbird (B1) combinator 來對同一個輸入進行sumlength的計算,並求得平均值。

// All the lines below are equivalent:
const avg1 = B1(div)(sum)(length);
const avg2 = arr => div(sum(arr))(length(arr));
const avg3 = arr => sum(arr) / length(arr);
const avg4 = arr => arr.reduce((a, x) => a + x, 0) / arr.length;

不要擔心看不明白,上面主要是為大家演示有 4 種方式來實現average功能。這就是 JavaScript 的優美之處。

相對來說,本文的內容是有點極客的。雖然筆者之前深度使用函數式語言 Haskell 做過不少研究項目,對函數式頗有理解,但是 point-free 風格的代碼,我們是不建議在實際工程中使用的,維護成本會很高。我們Fundebug所有的代碼都要求直觀易懂,不推崇用一些奇淫技巧來實現。除非某些萬不得已的地方,但是一定要把注釋寫得非常清楚,來降低后期的維護成本。

5. 終極優化: 一次計算出結果

之前所有的解法都可以很好地工作。那些使用reduce()的解法都有一個共同點,它們將大的問題拆解問小的子問題,然后通過不同的方式將它們組合起來。但是也要注意它們對數組遍歷了三次,感覺很沒有效率。如果一次就可以計算出來,才是最佳的方案。確實可以,不過需要一點數學運算。

為了計算 n 個元素的平均值,我們使用下面的公式:

那么,計算 n+1 個元素的平均值,使用同樣的公式(唯一不同的是 n 變成 n+1):

它等同於:

同樣等同於:

做點變換:

結論是,我們可以一直記錄當前狀態下的所有滿足條件的元素的平均值。只要我們知道之前所有元素的平均值和元素的個數。

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

const initialVals = { avg: 0, n: 0 };
const averagePopularity = victorianSlang.reduce(averageScores, initialVals).avg;
console.log("Average popularity:", averagePopularity);

這個方法只需要遍歷一次就計算出平均值,缺點是我們做了更多的計算。每一次當元素滿足條件,都要做乘法和除法,而不是最后才做一次除法。不過,它使用了更少的內存,因為沒有中間的數組變量,我們只是記錄了一個僅僅有兩個元素的對象。

這樣寫還有一個缺點,代碼一點都不直觀,后續維護麻煩。至少一眼看過去不能理解它是做什么的。

所以,到底哪一種方案才是最好的呢?視情形而定。也許你有一個很大的數組要處理,也許你的代碼需要在內存很小的硬件上跑。在這些場景下,使用第 5 個方案最佳。如果性能不是問題,那么就算使用最低效的方法也沒問題。你需要選擇最適合的。

還有一些聰明的朋友會思考:是否可以將問題拆解為子問題,仍然只遍歷一次呢?是的,確實有。需要使用 transducer。

關於Fundebug

Fundebug專注於JavaScript、微信小程序、微信小游戲、支付寶小程序、React Native、Node.js和Java線上應用實時BUG監控。 自從2016年雙十一正式上線,Fundebug累計處理了10億+錯誤事件,付費客戶有Google、360、金山軟件、百姓網等眾多品牌企業。歡迎大家免費試用

版權聲明

轉載時請注明作者Fundebug以及本文地址:
https://blog.fundebug.com/2019/06/05/5-ways-calculate-an-average-with-reduce/


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM