javascript - 编写具有多个参数的 javascript 函数

标签 javascript functional-programming ecmascript-6

如何将这个函数组合转换成更具可读性的格式?

funcA(argumentA, funcB(argumentA, funcC(argumentA, argumentB)))

我想要实现的更像是这样:

compose(funcC, funcB, funcA)(argumentA, argumentB)

我正在使用这个组合函数实现:

const compose = (...fns) => fns.reduce((f, g) => (...args) => f(g(...args)))

问题是我需要在所有函数调用中将 argumentA 作为第一个参数,并且每个函数返回一个值作为第二个参数传递给下一个函数。我知道我可以创建单独的函数返回函数并像这样使用它们:

compose(funcCWithArg(argumentA), funcBWithArg(argumentA), funcAWithArg(argumentA))(argumentB)

但在我的实际情况下,不仅有三个,还有更多,这将需要大量代码才能将它们写下来。有更简单的方法吗?

编辑:我不能使用任何外部库。只有 Vanilla js。

最佳答案

使用原生 JS,

const compose = (...fns) => (arg1, arg2) => fns.reduce((arg, f) => f(arg1, arg), arg2);

解释

compose 成为一个返回函数的函数,该函数循环遍历传递给它的函数列表,将第一个参数传递给每个函数调用。

测试

const sum = (a, b) => (a + b);
const mult = (a, b) => (a * b);
compose(sum, mult)(2, 3) === mult(2, sum(2, 3));  // true

关于javascript - 编写具有多个参数的 javascript 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44625410/

相关文章:

javascript - OpenLayers5 : hitTolerance doesn't seem to work with WMS layer

javascript - JQuery 如果悬停在任一元素上

javascript - 在 react 中获取输入值失败?

javascript - 如何在 Javascript 中推送代理对象中的数组值

javascript - Uncaught Error : Invariant Violation: Element type is invalid: expected a string

haskell - 一个函数,它接受一个列表并返回相同的列表,但不包含重复项

python - 如何压缩列表中的列表

math - 最大 : like argmax but gives the position(s) of the element x for which f[x] is maximal

javascript - 当react native出现这个错误时: transformClassesWithDexBuilderForDebug?

javascript - 如何在 css/js 中快速模糊?