我這個歲數的程序圓,學點東西不容易啊,不比你們精神小夥啊。
所以。
不廢話了,趕緊努力吧!
純函數的好處:
- 可緩存;
- 可單元測試;
- 並行處理,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));
每天寫寫博客,果然就是超越自己。哈哈哈!