示例代码:
// Compose functionality
const compose = (...fns) => {
return args => {
return fns.reduceRight((arg, fn) => fn(arg), args);
}
};
// List of transformation and predicate functions
const add1 = x => x + 1;
const isGreaterThanThree = x => x > 3;
const times2 = x => x * 2;
// Concat and Sum reducers (or the thing that I want to build).
/*
In this case, I'm using concatReducer, but I can easily substitute concatReducer with
sumReducer and change the initial value of the reduce method to zero.
*/
const concatReducer = (acc, el) => acc.concat(el);
const sumReducer = (acc, el) => acc += el;
// Transformation reducer (not sure the appropriate terminology)
const mapReducer = transform => {
return reducer => {
return (acc, el) => {
return reducer(acc, transform(el));
}
}
};
// Predicate reducer (again, not sure the appropriate terminology here)
const filterReducer = predicate => {
return reducer => {
return (acc, el) => {
return predicate(el) ? reducer(acc, el) : acc;
}
}
}
[1, 2, 3]
.reduce(
compose(
mapReducer(times2),
filterReducer(isGreaterThanThree),
mapReducer(add1),
)(concatReducer),
[]
);
我希望该值为 [ 8 ] 而不是 [ 5, 7 ]。
Compose 是右关联的 (reduceRight),但在这种情况下,它表现为左关联。
我心想,也许我的 compose 函数实现是错误的。结果,我拉入了ramda.js并使用了 R.compose,但得到了相同的结果。
难道我做错了什么?或者这是在处理传感器时组合是左关联的场景之一?