gpt4 book ai didi

javascript - 从头开始创建下划线 reduce 函数

转载 作者:数据小太阳 更新时间:2023-10-29 04:47:26 25 4
gpt4 key购买 nike

我正在努力创建自己的回调函数和高阶函数组。我坚持复制下划线减少功能或 ._reduce 功能。有人可以帮助我了解它是如何在引擎盖下工作的,这对我来说已经有几天了,我很困惑。这是我到目前为止所拥有的。请理解我没有使用下划线库,我正在尝试复制它以便我可以进一步了解高阶函数。谢谢。

var reduce = function(collection, iterator, accumulator) {

var iterator = function(startPoint, combiner){
for(var i = 0; i <combiner.length; i++){
startPoint += combiner[i];
}
return iterator(accumulator, collection);
}

最佳答案

一个简单的递归函数就可以了

// arr - some array of values
// f - the reducing function
// acc - initial value for the accumulator
function reduce(arr, f, acc) {
if (arr.length === 0)
return acc
else
return reduce(arr.slice(1), f, f(acc, arr[0]))
}

// --------------------------------------------------

// example 1:
// reduce an array of numbers using an adding function

var ex1 = reduce([1,2,3], function(acc, x) { return acc + x }, 0)

console.log(ex1)
//=> 6

// --------------------------------------------------

// example 2:
// reduce an array of pairs to a mapping object

var ex2 = reduce([['a', 1], ['b', 2], ['c', 3]], function(acc, pair) {
var key = pair[0]
var value = pair[1]
acc[key] = value
return acc
}, {})

console.log(ex2)
//=> { a: 1, b: 2, c: 3 }


正如@torazaburo 在评论中指出的那样,如果您可以使用 ES6,解构赋值将进一步清理实现

// ES6
function reduce([x, ...xs], f, acc) {
if (x === undefined)
return acc
else
return reduce(xs, f, f(acc, x))
}

或者用箭头函数让它变得 super 甜

// ES6, same as above but using arrow function and ternary expression
const reduce = ([x, ...xs], f, acc)=>
x === undefined ? acc : reduce(xs, f, f(acc, x))

Underscore 实现确实提供了一些其他便利,但我猜这些是为了保持与原生 Array.prototype.reduce 的兼容性。 .我个人不会以这种方式实现 reduce,但这不是重点。

  1. Underscore 将迭代器和 arr 引用传递给回调函数。
  2. 下划线允许您更改回调函数的上下文

这是支持这些其他功能的修改后的实现

// our reduce version 2.0
function reduce(collection, iterator, memo, context) {
function loop(memo, i) {
if (collection.length === i)
return memo
else
return loop(iterator.call(context, memo, collection[i], i, collection), i + 1)
}
return loop(memo, 0)
}

您可以像上面一样使用它,只是现在它为回调提供了更多信息

注意

我有目的地决定实现 Underscore 的 reduce 行为,该行为允许您在没有初始值的情况下执行归约。支持这种行为会导致代码不安全,并且一开始就不应该将其放入 Underscore 中。

关于javascript - 从头开始创建下划线 reduce 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38087989/

25 4 0
文章推荐: javascript - 根据规则绑定(bind)到对象上任意深度的属性
文章推荐: javascript - 当循环遍历 JS 数组的值并删除值时,是否需要使用 while 而不是 for?
文章推荐: javascript - d3 力导向布局 - 链接距离优先
文章推荐: c# - 如何在 C# 中将 List 转换为 Hashtable?