Javascript Array reduce(iteratee, initialValue)

Description

Javascript Array reduce(iteratee, initialValue)



Array.prototype.reduce = function(iteratee, initialValue) {
 if (typeof iteratee !== "function") {
  throw new TypeError(iteratee + ' is not a function')
 }
 let arr = this;/*from w w w .j  a v  a 2s  .  c  om*/
 let len = arr.length;
 let result;
 let index;
 if (initialValue != void 0) {
  result = initialValue;
  index = 0;
 } else {
  result = arr[0];
  index = 1;
 }

 function loop() {
  if (len > 0) {
   result = iteratee.call(null, result, arr[index]);
   len--
   index++;
   loop();
  }
 }
 loop();
 return result;
}



PreviousNext

Related