[英]How would I write a recursive function that sums an array of numbers that uses tail call optimization (TCO)?
So I wrote this function that sums an array of numbers using recursion. 所以我编写了这个函数,使用递归对一组数字进行求和。 How would I make this tail call optimized?
如何优化尾调用?
function sum(array) {
if (array.length === 0) {
return 0;
} else {
return array[0] + sum(array.slice(1));
}
}
sum([1, 2, 3, 4, 5]); // 15
A TCO function needs to return a function call, which replaces the last stack item and prevents the stack to grow. TCO函数需要返回一个函数调用,它会替换最后一个堆栈项并阻止堆栈增长。
Therfore you need to store the total
as well in the function as parameter and hand over this value at the ent of the recursion. 因此,您需要将
total
也存储在函数中作为参数,并在递归时移交此值。
function sum(array, total = 0) { if (array.length === 0) { return total; } return sum(array.slice(1), total + array[0]); } console.log(sum([1, 2, 3, 4, 5])); // 15
Using Array.prototype.reduce() there is no need to do a recursive function: 使用Array.prototype.reduce()不需要执行递归函数:
const result = [1, 2, 3, 4, 5].reduce((a, c) => a + c, 0); // 15 console.log(result);
Just use a ternary operator like so: 只需使用三元运算符,如下所示:
const sum = array => array.length ? array[0] + sum(array.slice(1)) : 0; console.log(sum([1, 2, 3, 4, 5])); // 15
You can also use Array.prototype.reduce
to avoid recursion: 您还可以使用
Array.prototype.reduce
来避免递归:
const sum = array => array.reduce((acc, curr) => acc + curr, 0); console.log(sum([1, 2, 3, 4, 5]));
You can't, tail call optimization (TCO) is not supported in most of browser. 你不能,大多数浏览器都不支持尾调用优化(TCO)。 You can see support info here .
您可以在此处查看支持信息。
You can always use for loop. 你总是可以使用for循环。 for loop has higher performance in most of situation.
for循环在大多数情况下具有更高的性能。
function getRandomInt(min, max) { min = Math.ceil(min); max = Math.floor(max); return Math.floor(Math.random() * (max - min)) + min; //不含最大值,含最小值} function sum_1(arr) { var s = 0; for (var i = 0; i < arr.length; i++) { s += arr[i]; } return s; } function sum_2(arr){ return arr.reduce((a, c) => a + c, 0); } var arr = []; for (var i = 0; i < 10000000; i++) { arr[i] = getRandomInt(0,100); } let t0 = window.performance.now(); sum_1(arr); // 15 let t1 = window.performance.now(); console.log("sum_1 executed time : " + (t1 - t0) + " ms"); let t2 = window.performance.now(); sum_2(arr); // 15 let t3 = window.performance.now(); console.log("sum_2 executed time : " + (t3 - t2) + " ms");
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.