JavaScript 如何将函数展开至n层
以下方法介绍了如何在JavaScript中将函数展开至n层。函数的展开是将函数参数进行包装,并一次性传递所有参数的过程。展开至n层意味着我们只传递n个参数。
可以通过以下方法实现:
- 使用reduce()方法
- 使用for-of循环方法
使用reduce()方法
reduce方法用于对列表的所有元素应用操作并返回结果。它接受一个对所有元素应用的回调函数。为了将args切片至n层,我们使用slice()方法。slice()方法从列表中提取部分元素。slice()方法接受起始索引和终止索引,用于提取元素的范围。如果没有提供起始索引,默认为0。可以提供终止索引,直到列表的末尾。
示例:
<script>
// Uncurry that unwrap function
let uncurry = (f, n) => (...args) => {
// Function that apply function to all elements
let func = f => a => a.reduce((l, m) => l(m), f)
// If args are less than n return
if (n > args.length)
return " less args provide ";
// Apply function up to n
return func(f)(args.slice(0, n));
}
let n = 3;
// Function sum three values
const sum = x => y => z => x + y + z;
let t = uncurry(sum, n);
let ans = t(1, 2, 4, 5);
console.log(`Sum of {n} args are{ans}`);
</script>
输出:
Sum of 3 args are 7
使用for-of循环方法
在这种方法中,我们使用for-of循环。for-of循环用于遍历列表的所有元素。以下是该方法的实现:
- 定义n和sum函数,用于将所有提供的参数相加。
- 使用sum、n和所有数字列表调用uncurry函数。
- uncurry函数检查n是否大于参数,然后返回更少的参数。
- 否则,它遍历整个参数,并将sum函数应用于每个参数。
- 在for循环中,我们计算迭代次数。当迭代次数等于n时,退出循环。
- 最后返回f,它是所有传入元素的总和。
示例:
// Sum function that we have to uncurry
const sum = x => y => z => x + y + z;
// Function that uncurry function up-to
// n depth with for loop
const uncurry = f => n => {
let k = 0;
return (...args) => {
if (n > args.length) {
return "n";
}
for (let arg of args) {
if (k === n)
break;
k++
f = f(arg);
}
return f
};
}
// Creating uncurry function with sum function and 3 value
let n = 3;
const uncurried = uncurry(sum)(n);
let ans = uncurried(0, 1, 7, 2, 4);
console.log(`Sum of {n} args is{ans}`);
输出:
Sum of 3 args is 8
极客教程