【问题标题】:Partial functions with bind带绑定的部分函数
【发布时间】:2018-06-05 20:10:21
【问题描述】:

所以最近我发现你可以使用 bind 用 js 做部分函数/currying。 例如:

const foo = (a, b, c) => (a + (b / c))
foo.bind(null, 1, 2) //gives me (c) => (1 + (2 / c))

但这只有在你想咖喱的部分是有序的情况下才有效。如果我想使用 bind 实现以下目标怎么办?

(b) => (1 + (b / 2))

尝试了各种解决方案,例如:

foo.bind(null, 1, null, 2)

有什么想法吗?有没有可能用 vanilla es6 来完成这个?

【问题讨论】:

标签: javascript ecmascript-6 bind currying partial-application


【解决方案1】:

您可以使用包装器对参数进行重新排序。

const
    foo = (a, b, c) => a + b / c,
    acb = (a, c, b) => foo(a, b, c);

console.log(acb.bind(null, 1, 2)(5));

【讨论】:

    【解决方案2】:

    目前我在考虑两种方法来实现这一点(除了来自@NinaSholz 的包装器,它非常好):

    1。使用合并两个参数数组的curry 函数:

    const foo = (a, b, c) => a + b / c;
    
    function curry(fn, ...args) {
      return function(...newArgs) {
        const finalArgs = args.map(arg => arg || newArgs.pop());
        return fn(...finalArgs);
      };
    }
    
    const curriedFoo = curry(foo, 1, null, 2);
    
    console.log(curriedFoo(4)) // Should print 1 + 4 / 2 = 3

    这里我们只是发送nullundefined 来代替我们想要跳过的参数,并且在第二次调用中我们按顺序发送这些参数

    2。为命名参数使用对象

    const foo = ({a, b, c}) => a + b / c;
    
    function curry(fn, args) {
      return (newArgs) => fn({ ...args,
        ...newArgs
      });
    }
    
    const curriedFoo = curry(foo, {
      a: 1,
      c: 2
    });
    
    console.log(curriedFoo({
      b: 4
    }));

    这里我们利用函数签名中的...(spread) 运算符和对象语法来合并两个参数对象;

    【讨论】:

      猜你喜欢
      • 2014-02-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-03-24
      • 1970-01-01
      • 2014-01-18
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多