reduce

原生的reduce方法只適用于數(shù)組,且方向固定為從左向右。

underscore中的reduce與reduceRight分別支持兩個方向的迭代,且支持對對象的操作。

 _.reduce = _.foldl = _.inject = createReduce(1);
 _.reduceRight = _.foldr = createReduce(-1);

其底層實現(xiàn)均為createReduce方法。

createReduce

//dir決定迭代方向,-1為從右向左,1為從左向右
var createReduce = function(dir) {
    // Wrap code that reassigns argument variables in a separate function than
    // the one that accesses `arguments.length` to avoid a perf hit. (#1991)
    //這里是迭代的核心函數(shù)
    var reducer = function(obj, iteratee, memo, initial) {
      //處理數(shù)組與對象的不同
      var keys = !isArrayLike(obj) && _.keys(obj),
          length = (keys || obj).length,
          //迭代方向
          index = dir > 0 ? 0 : length - 1;
      //是否提供最初與數(shù)組或?qū)ο筮M行迭代的數(shù)據(jù)
      if (!initial) {
        memo = obj[keys ? keys[index] : index];
        //需要將起始位置向迭代方向移動一位
        index += dir;
      }
      //迭代
      for (; index >= 0 && index < length; index += dir) {
        var currentKey = keys ? keys[index] : index;
        memo = iteratee(memo, obj[currentKey], currentKey, obj);
      }
      return memo;
    };

    return function(obj, iteratee, memo, context) {
      //initial變量標識是否提供最初的迭代數(shù)據(jù)
      var initial = arguments.length >= 3;
      return reducer(obj, optimizeCb(iteratee, context, 4), memo, initial);
    };
  };
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容