这是我试图理解的一段代码:
const seq2 = (f1, f2) => {
return (...args) => {
return f2( f1( ...args) );
}
}
const seq = ( f1, ...fRest) =>
fRest.reduce( seq2, f1 );
const elevator = {
floor: 5
};
const up = elevator => {
return {
floor: elevator.floor + 1
}
};
const down = elevator => {
return {
floor: elevator.floor - 1
}
};
const move = seq( up, up, down, up);
const newElevator = move( elevator );
console.log( newElevator.floor ) // shows 7
这是js函数式编程类(class)中的一个例子。我想弄清楚我是否可以简化 seq 函数,让它看起来像这样
const seq = ( ...fRest) =>
fRest.reduce(seq2);
????
为什么我必须将 f1
作为第一个参数传递,然后将其作为 initialValue
进一步传递给 reduce 方法,是否有任何特定原因?当我不在 reduce 方法中指定 initialValue
时,它不会默认将第一个数组元素 - accumulator
- 作为 initialValue
?如果有人可以向我解释该代码中发生了什么,我将不胜感激:)
最佳答案
seq()
会尝试减少没有累加器的空数组,这是一个错误 – 而不是 f1
以作者在此处编写的方式修复此问题。
initialValue
– Value to use as the first argument to the first call of thecallback
. If no initial value is supplied, the first element in the array will be used. Callingreduce()
on an empty array without an initial value is an error – source MDN: Array.prototype.reduce
当 seq()
用于构建空序列时,seq
的更健壮的实现不会导致错误
const identity = x =>
x
const seq2 = (f, g) =>
(...args) => f (g (...args))
const seq = (...fs) =>
fs.reduce (seq2, identity)
const up = elevator =>
({ floor: elevator.floor + 1 })
const down = elevator =>
({ floor: elevator.floor - 1 })
console.log
( seq (up, up, down, up) ({ floor: 3 }) // { floor: 5 }
, seq () ({ floor: 3 }) // { floor: 3 }
)
seq
的简化版本,通过禁止可变函数的组合来促进更好的功能卫生
const identity = x =>
x
const seq = (f = identity, ...rest) =>
f === identity
? f
: x => seq (...rest) (f (x))
const up = elevator =>
({ floor: elevator.floor + 1 })
const down = elevator =>
({ floor: elevator.floor - 1 })
console.log
( seq (up, up, down, up) ({ floor: 3 }) // { floor: 5 }
, seq () ({ floor: 3 }) // { floor: 3 }
)
关于javascript - 链接和函数组合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51954475/