我想知道是否可以找出柯里化(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
,它需要一个选项参数和一个要调用的函数数组。我想通过函数数组进行“管道
”,并将选项参数仅输入到实际需要该参数的函数,如本例中的 divideBy
和 decrementAndDivideBy
,例如:
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
参数,但遗憾的是这是不可能的。
您还应该注意,double
、inc
、divideBy
和 decrementAndDivideBy
构建为仅接受数字参数 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/