pipe函数
pipe函数和compose函数一样,都是用来管理执行其他 函数的函数。
区别在于compose里面的函数是从右像左执行的,而pipe函数是从左像右执行的。
链式调用
其实大家应该也能想到,为了方便函数调用,我们完全可以改造成链式调用的形式去组织我们函数的执行。
我们就用Promise的then方法来进行链式调用,丰富我们的函数式编程。
function addNum(num){
return ++num
}
function multiply(num){
return num *2
}
Promise.resolve(2).then(addNum).then(multiply).then(res=>console.log(res))
高阶函数
我们可能经常听别人说高阶函数。那么高阶函数究竟是什么呢?其实它一点都不陌生,甚至你用到了高阶函数可能自己不知道而已。
如果一个函数A的参数也是一个函数,那么函数A就是高阶函数。
所以常用了forEach,filter,reduce,some这些,都是高阶函数。
手写forEach体会高阶函数
Array.prototype.forEach2 = function(callBack){
let len = this.length
if(typeof callBack !== 'function'){
throw new Error('must be function')
}
for(let i =0;i<len;i++){
callBack.call(this,this[i],i)
}
}
let arr = [2,3,4]
arr.forEach2(item=>{
console.log(item)
})