javascript(函數式編程思考) ---> Map-Filter
阿新 • • 發佈:2017-08-26
urn 函數式編程 回調 ons 元素 nbsp script arr 對象
let add = x=>x+1; //Map :: (a -> b) -> [a] -> [b] let Map = (function(result,f,arr){ //閉包存儲累積對象 let result = []; return function map(f,arr){ if(!Array.isArray(arr)){ return "要處理的對象為數組"; } if(arr.length ==0){ return[]; }else{ let [head,...tail] = arr; result.push(f(head)); // 通過回調map遍歷目標對象arr,f處理過的元素存入result,tail為[]即遍歷結束,可以返回result return tail.length == 0 ? result : map(f,tail); } } })(); let test = Map(add,[1,2,3]); console.log(test);//[2,3,4]
let biggerTen = x => x>10;
//Filter :: (a -> Bool) -> [a] -> [a] let Filter = (function(){ let result=[]; return function filter(f,arr){ if(!Array.isArray(arr)){ return "要處理的對象為數組"; } if(arr.length == 0){return []; }else{ let [head,...tail] = arr; f(head) && result.push(head); return tail.length == 0 ? result : filter(f,tail); } }; })(); let testFilter = Filter(biggerTen,[1,5,10,44,12,2,5]); console.log(testFilter);//[44,12]
javascript(函數式編程思考) ---> Map-Filter