javascript - 检查柯里化(Currying)函数是否仍需要更多参数

标签 javascript functional-programming currying

我想知道是否可以找出柯里化(Currying)函数在 javascript 中需要多少个剩余参数(如果可能的话),而无需实际调用该函数。 我想要一个函数,它接受一个函数,并在该函数需要 2 个或更多剩余参数时返回。

hasSeveralRemainingArguments: fn => bool

假设我有以下功能:

const double = x => 2*x;
const inc = x => x + 1;
const divideBy = ({dividor}) => x => x/dividor;
const decrementAndDivideBy = ({dividor}) => x => (x - 1)/dividor;

hasSeveralRemainingArguments(double); // false
hasSeveralRemainingArguments(inc); // false
hasSeveralRemainingArguments(divideBy); // true
hasSeveralRemainingArguments(divideBy({dividor: 5})); // false
hasSeveralRemainingArguments(decrementAndDivideBy); // true
hasSeveralRemainingArguments(decrementAndDivideBy({dividor: 5})); // false

用例是一个函数foo,它需要一个选项参数和一个要调用的函数数组。我想通过函数数组进行“管道”,并将选项参数仅输入到实际需要该参数的函数,如本例中的 divideBydecrementAndDivideBy ,例如:

const pipe = (...fns) => x => fns.reduce((y, fn) => fn(y), x);

const foo = (options = {}) => (fns = []) => pipe(
  fns.map(fn => (
    hasSeveralRemainingArguments(fn) ? 
      fn(options) : 
      fn
  )
);

const bar = (...fns) => {
  const options = {
    dividor: 3
  }; // local, not known to the caller of bar. They just know that they can pass in a function which will receive an options-object, they just don't know what is inside this object.

  return foo(options)(fns);
});

const baz = bar(
  double,
  inc, 
  divideBy,
  decrementAndDivideBy
);

baz(4); // ((4*2 + 1)/3 - 1)/3 = 0.67
baz(10); // ((10*2 + 1)/3 - 1)/3 = 2

函数 bar 的调用者不知道 options 参数。否则,我可以在将函数传递到 bar 之前输入 options 参数,但遗憾的是这是不可能的。

您还应该注意,doubleincdivideBydecrementAndDivideBy 构建为仅接受数字参数 x 但情况可能并不总是如此。如果可能的话,我不想调用函数并测试返回值是否是函数,但目前我没有看到任何其他方法。

我还可以传递带有函数和 bool 值“isExpectingOptions”的对象,但这对于调用 bar 的人来说不是很好/优雅。

你还有其他想法吗?

最佳答案

您是否考虑过使用 length函数的属性?

The length property indicates the number of parameters expected by the function.

const a = curry((x, y, z) => 42);

a.length       // 3
a(1).length    // 2
a(1)(2).length // 1

关于javascript - 检查柯里化(Currying)函数是否仍需要更多参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62371876/

相关文章:

javascript - 我们可以在 MooTools/Jquery 选择器中使用 OR 运算符吗

lambda - 用 rust 编写的替代功能样式

javascript - 使用可选属性实例化类的正确方法

java - 我可以按元素的类过滤 Stream<T> 并一步获得 Stream<U> 吗?

haskell - 是否可以将 F# 记录的标签用作 Haskell 中的函数或类似的函数?

javascript - 如何正确序列化 Javascript curry 箭头函数?

haskell - 无法理解以未部分应用的函数作为参数提供的高阶函数调用的结果

function - scala隐式类方法类型不匹配在reduce与函数currying的非隐式方法中

javascript - 如何在 React 上读取事件中的 Prop

javascript - 这是Javascript的特殊字符串格式