在箭头函数内部,还可以再使用箭头函数
先看个ES5语法的多重嵌套函数
function insert(value) {
return {
into: function(array) {
return {
after: function(afterValue) {
array.splice(array.indexOf(afterValue) + 1, 0, value);
return array
}
}
}
}
}
console.log(insert(1).into([1, 3]).after(1)); //[1, 1, 3]
console.log(insert(5).into([1, 3]).after(3)); //[1, 3, 5]
用箭头函数改写上面函数
let insert = (value) => ({
into: (array) => ({
after: (afterValue) => {
array.splice(array.indexOf(afterValue) + 1, 0, value);
return array
}
})
})
console.log(insert(1).into([1, 3]).after(1)); //[1, 1, 3]
console.log(insert(5).into([1, 3]).after(3)); //[1, 3, 5]
再举一个部署管道机制的,即前一个函数的输出是后一个函数的输入
const pipeline = (...funcs) => val => funcs.reduce((a, b) => b(a), val)
const plus = a => a + 1;
const mult = a => a * 2;
const addThenMult = pipeline(plus, mult);
console.log(addThenMult(5)); // 12
console.log(addThenMult(8)); // 18
下面这种写法同上,可读性比较强一些
const pipeline = (...funcs) => val => funcs.reduce((a, b) => b(a), val)
const plus = a => a + 1;
const mult = a => a * 2;
console.log(mult(plus(5))); // 12
console.log(mult(plus(8))); // 18