ramda.js - 使用 bind this 将参数传递到管道

标签 ramda.js

我经常创建一个小函数管道。在管道中的某个点,比方说在第 3 级,一个函数可能需要传递一个先前函数不需要的参数。

我可以模拟管道中第一个函数的多次返回,返回一个带有不需要的参数的对象,但我不确定这是一个好的做法。所以我使用 bind 和 this 在我需要的地方专门传递参数:

function errorMessageBag( fields, model ) {
    const execution = R.pipe( normalizedFormFields,
                              mergedModelAndFormFields.bind( this, model ), // Here I pass an argument only needed by this function
                              fieldsWithValidation,
                              requiredFields,
                              stringLengthValidation,
                              emailValidation,
                              urlValidation )

    return execution( fields ) // Parameter respects signature of first function in the flow.
}

你看到在这个例子中我传递给 mergedModelAndFormFields 一个参数,模型。 工作正常,但这是常见做法还是不良做法?如果不好,处理这个问题的正确方法是什么?

最佳答案

我认为这种方法没有任何问题。

你总是可以定义一个内部函数并在管道中使用它:

function errorMessageBag(fields, model) {
    const execution = R.pipe(normalizedFormFields,
                          mergedModelAndFormFieldsWrapped,
                          fieldsWithValidation,
                          requiredFields,
                          stringLengthValidation,
                          emailValidation,
                          urlValidation);

    return execution(fields)

    function mergedModelAndFormFieldsWrapped(fields) { 
        // model is accessible here
    }
}

关于ramda.js - 使用 bind this 将参数传递到管道,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38523687/

相关文章:

javascript - 无法使用 R.path 获取输入值

javascript - 如何使用 Ramda 将代码从 Lisp(MIT Schema)翻译成 JavaScript?

javascript - 如何使用 Ramda 将对象数组映射到单个对象

javascript - 用 Ramda 大写字符串数组

javascript - Ramda 或 ES6 - 在过滤对象数组后返回对象属性的值

javascript - Ramda.js 如何用挖掘对象进行采摘

javascript - Ramda - 部分应用的功能取决于完整的应用

javascript - 如何在 vanilla JS 中重写这个 ramda.js 代码

functional-programming - curry 函数中的反向参数顺序(ramda js)

函数返回函数时的 TypeScript 类型推断问题