How to early break reduce() method?

后端 未结 12 1217
忘掉有多难
忘掉有多难 2020-11-28 05:44

How can I break the iteration of reduce() method?

for:

for (var i = Things.length - 1; i >= 0; i--) {
  if(Things[i] <=         


        
12条回答
  •  天涯浪人
    2020-11-28 06:46

    As the promises have resolve and reject callback arguments, I created the reduce workaround function with the break callback argument. It takes all the same arguments as native reduce method, except the first one is an array to work on (avoid monkey patching). The third [2] initialValue argument is optional. See the snippet below for the function reducer.

    var list = ["w","o","r","l","d"," ","p","i","e","r","o","g","i"];
    
    var result = reducer(list,(total,current,index,arr,stop)=>{
      if(current === " ") stop(); //when called, the loop breaks
      return total + current;
    },'hello ');
    
    console.log(result); //hello world
    
    function reducer(arr, callback, initial) {
      var hasInitial = arguments.length >= 3;
      var total = hasInitial ? initial : arr[0];
      var breakNow = false;
      for (var i = hasInitial ? 0 : 1; i < arr.length; i++) {
        var currentValue = arr[i];
        var currentIndex = i;
        var newTotal = callback(total, currentValue, currentIndex, arr, () => breakNow = true);
        if (breakNow) break;
        total = newTotal;
      }
      return total;
    }

    And here is the reducer as an Array method modified script:

    Array.prototype.reducer = function(callback,initial){
      var hasInitial = arguments.length >= 2;
      var total = hasInitial ? initial : this[0];
      var breakNow = false;
      for (var i = hasInitial ? 0 : 1; i < this.length; i++) {
        var currentValue = this[i];
        var currentIndex = i;
        var newTotal = callback(total, currentValue, currentIndex, this, () => breakNow = true);
        if (breakNow) break;
        total = newTotal;
      }
      return total;
    };
    
    var list = ["w","o","r","l","d"," ","p","i","e","r","o","g","i"];
    
    var result = list.reducer((total,current,index,arr,stop)=>{
      if(current === " ") stop(); //when called, the loop breaks
      return total + current;
    },'hello ');
    
    
    console.log(result);
    

提交回复
热议问题