Сообщение от Vjacheslav143
|
2. Write the same reduce2 recursively (do not simulate a cycle through recursion)
Hints:
slice
|
<script src="http://stacksnippets.net/scripts/snippet-javascript-console.min.js?v=1"></script>
<script>
Array.prototype.reduce2 = function(c, a) {
var b = this.slice(0);
1 == arguments.length && (a = b.shift());
b.length && (a = c(a, b.shift()), a = b.reduce2(c, a));
return a
};
function add(a, b) { return a + b }
function mul(a, b) { return a * b }
function foo(a, b) { return a.concat(b) }
var a = [1, 2, 3, 4]
console.log(a.reduce(add), a.reduce2(add)) // 10 10
console.log(a.reduce(add, 10), a.reduce2(add, 10)) // 20 20
console.log(a.reduce(mul), a.reduce2(mul)) // 24 24
console.log(a.reduce(foo, ''), a.reduce2(foo, '')) // 1234 1234
</script>