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]
时间: 2024-11-12 13:08:19