在《重构》这本书里提到了一个改善程序的方法,“以管道取代循环(Replace Loop with Pipeline)”。
1 2 3 4 5
| const names=[]; for(const i of input){ if(i.job==="programmer") names.push(i.name); }
|
1
| const names=input.filter(i => i.job==="programmer").map(i=>i.name);
|
1 2 3 4 5
| const nums=[10,20,111,222,444,40,50]; let total=nums.filter(n=>n<100).map(n=>n*2).reduce((pre,n)=>pre+n); console.log(total); ------------------------------------------------------------------------ 240
|
集合管道(collection pipeline)允许使用一组运算来描述集合的迭代过程,其中每种运算接受的入参和返回值都是一个集合。这类运算有很多,map是指用一个函数作用于输入集合的每一个元素,将集合变换成另一个集合;filter运算时指用用一个函数从输入集合筛选出符合条件元素子集的过程。运算得到的集合可以供管道的后续流程使用;而reduce运算是通过输入做一个数组,最后经过进行汇总运算最后输出一个值。
在许多不同的语言中也有函数式编程的方法。
例如在php中:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26
| class Test {
protected $nums=[1,2,3,4,5,6,7]; public function count() { $nums=$this->nums; $result=array_reduce(array_map(function ($num){ return $num*$num; },array_filter($nums,function ($num){ return $num >= 5; })),function ($preValue,$num){ return $preValue+$num; },0); echo $result; } }
function main() { $test=new Test(); $test->count(); } main(); ----------------------------------------------------------------------------------------- 110
|