函数组合中的条件运算

Mar*_*oni 7 javascript functional-programming function function-composition

如何根据某些逻辑条件停止或分支合成?

例如.假设我有以下代码:

compose(
  operation4
  operation3,
  operation2,
  operation1
)(myStuff);
Run Code Online (Sandbox Code Playgroud)

甚至是类似的东西

myStuff
 .map(operation1)
 .map(operation2)
 .map(operation3)
 .map(operation4)
Run Code Online (Sandbox Code Playgroud)

如果myStuff满足某些条件,我只希望执行操作3和4.

我该如何实现(特别是在JavaScript中)?

我是否必须创建两个较小的组合并具有单独的if语句,或者是否有办法在组合中包含条件?

Monads可以解决我的问题吗?如果是这样,怎么样?

geo*_*org 9

一个简单但实​​用的方法是有一个函数,比如when(cond, f)f只有在cond(x)返回 true时才执行(反过来可以是一个组合):

_do = (...fns) => x => fns.reduce((r, f) => f(r), x);
_when = (cond, f) => x => cond(x) ? f(x) : x;


// example

add3 = x => x + 3;
add5 = x => x + 5;
add9 = x => x + 9;


pipe = _do(
    add3,
    add5,
    _when(x => x > 20, _do(add9))
)


console.log(pipe(30))
console.log(pipe(1))
Run Code Online (Sandbox Code Playgroud)


Евг*_*чев 0

只需在每个步骤后分析您的someObject即可。带有条件回调的示例,但您可以通过不同的方式实现此检查。

function compose(...fns) {
    return function (result, conditionCallback) {
        for (var i = fns.length - 1; i > -1; i--) {
            result = fns[i].call(this, result);

            // Run here condition check if provided.
            if (conditionCallback && conditionCallback(result) === false) {
                return result;
            }
        }
        return result;
    };
};

compose(...functionList)(someObject, function(obj) {
    return obj.prop !== someValue;
});
Run Code Online (Sandbox Code Playgroud)

PS:我希望理解正确,你所说的“构图”是什么意思。

PPS:示例使用了 ES6 功能,但降级到 ES5 非常简单。