我正在尝试在 JavaScript 中创建一个动态组合其他函数的函数。目标是传递一个函数数组并接收一个按顺序应用每个函数的新函数。但是,我希望能够在组合过程中将参数传递给每个函数。
const add = (a, b) => a + b;
const multiply = (a, b) => a * b;
const subtract = (a, b) => a - b;
const composedFunction = composeFunctions([add, multiply, subtract], 2, 3);
const result = composedFunction(); // Should return the result of subtract(multiply(add(2, 3)))
如何实现 composeFunctions 函数以通过参数传递来实现这种动态组合?我对允许灵活数量的函数和参数的解决方案特别感兴趣。
任何见解或代码示例将不胜感激!预先感谢。
这是我迄今为止尝试过的:
function composeFunctions(funcArray, ...args) {
return function() {
let result = args;
funcArray.forEach(func => {
result = func(...result); // Doesn't work
});
return result;
};
}
const add = (a, b) => a + b;
const multiply = (a, b) => a * b;
const subtract = (a, b) => a - b;
const composedFunction = composeFunctions([add, multiply, subtract], 2, 3);
const result = composedFunction(); // This doesn't work as expected
console.log(result);
这是针对您的用例的更正且完整的实现:
关键的改进在于应用每个函数的循环。结果在传递给序列中的下一个函数之前被包装在一个数组中。
最后通过访问数组的第一个元素来提取最终结果。
这是您的更新代码:
function composeFunctions(funcArray, ...args) {
return function() {
let result = args;
for (const func of funcArray) {
result = [func(...result)]; // Ensure the result is wrapped in an array for the next iteration
}
return result[0]; // Extract the final result from the array
};
}
const add = (a, b) => a + b;
const multiply = (a, b) => a * b;
const subtract = (a, b) => a - b;
const composedFunction = composeFunctions([add, multiply, subtract], 2, 3);
const result = composedFunction();
console.log(result); // Output: -1