javascript - 递归实现函数reduce javascript

标签 javascript recursion reduce

我想编写一个递归版本的reduce函数。

Array.prototype.reduce2 =
function reduce(fn, initial) {
  var head = this[0];
  var tail = this.slice(1);
  var result = fn(initial, head, 0, tail);
  return reduce(tail, fn, result);
}

var a = [1, 2, 3, 4];

function add(a, b) { return a + b }  ;
function mul(a, b) { return a * b }  ;
function foo(a, b) { return a.concat(b) };

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(add, undefined), a.reduce2(add, undefined)); // NaN NaN
console.log(a.reduce(mul), a.reduce2(mul));                       // 24 24
console.log(a.reduce(foo, ''), a.reduce2(foo, ''));               // 1234 123

结果是:

10 [Function: add]
20 [Function: add]
NaN [Function: add]
24 [Function: mul]
1234 function foo(a, b) { return a.concat(b) }

是的,我知道这看起来有很多主题,但我找不到答案。

最佳答案

您应该避免向 native 对象添加方法。

您可以使用参数解构以更简单的方式对简单函数执行相同的操作。

function reduce(fn, initial, [head, ...tail]) {
  return tail.length
    ? reduce(fn, fn(initial, head), tail)
    : fn(initial, head)
}

Array.prototype.reduce2 = function(fn, initial) {
  const head = this[0]
  const tail = Array.prototype.slice.call(this, 1)
  return tail.length
    ? tail.reduce2(fn, fn(initial, head))
    : fn(initial, head)
}

const a = [1, 2, 3, 4];

const add = (a, b) => a + b
const mul = (a, b) => a * b
const foo = (a, b) => a.concat(b)

console.log(
  reduce(add, 0, a),
  a.reduce(add, 0),
  a.reduce2(add, 0)
)

console.log(
  reduce(mul, 1, a),
  a.reduce(mul, 1),
  a.reduce2(mul, 1)
)

console.log(
  reduce(foo, '', a),
  a.reduce(foo, ''),
  a.reduce2(foo, '')
)

console.assert(
  a.reduce2(add, 0) === 10,
  'reduce2 can sum numbers'
)
console.assert(
  a.reduce2(mul, 1) === 24,
  'reduce2 can multiply numbers'
)
console.assert(
  a.reduce2(foo, '') === '1234',
  'reduce2 can contatinate strings'
)
<script src="https://codepen.io/synthet1c/pen/KyQQmL.js?tab=assert"></script>

关于javascript - 递归实现函数reduce javascript,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48381594/

相关文章:

java - 使用递归检查整数的位数是否为偶数

iOS Swift - 减少功能

javascript - 从 typescript 中的通用类扩展的类扩展

javascript - 使用 javascript 黑莓应用程序启动默认/ native 浏览器

javascript - 通过标签获取最近的前一个兄弟

python - Python 中的列表在使用替换方法时不维护值

c++ - 递归函数扫描字符串添加ASCII

python - 有没有办法在 Python 中指定 reduce() 累加器?

parallel-processing - 使用 OpenMP 减少 : linear merging or log(number of threads) merging

javascript - 获取 WebAssembly 导出函数的地址?