1-13、純函數的好處

我這個歲數的程序圓,學點東西不容易啊,不比你們精神小夥啊。

所以。

不廢話了,趕緊努力吧!

純函數的好處:

  1. 可緩存;
  2. 可單元測試;
  3. 並行處理,ES6以後可以通過(web worker)開啓多線程。在多線程處理過程中,不需要訪問共享的內存數據,可以任意運行。

可緩存,示例1:

// 安裝loadsh庫,npm i -D loadsh
const _ = require('loadsh');
function getArea(r) {
    console.log(r);
    return Math.PI * r * r;
}

let getAreaWithMemory = _.memoize(getArea);
console.log(getAreaWithMemory(4));
console.log(getAreaWithMemory(4));
console.log(getAreaWithMemory(4));

模擬memoize()函數, 示例2:

function memoize (f) {
    let cache = {}
    return function () {
        let key = JSON.stringify(arguments);
        cache[key] = cache[key] || f.apply(f, arguments);
        return cache[key];
    }
}
let getAreaWithMemory = memoize(getArea);
console.log(getAreaWithMemory(4));
console.log(getAreaWithMemory(4));
console.log(getAreaWithMemory(4));

每天寫寫博客,果然就是超越自己。哈哈哈!

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章