Javascript Array myInject(func)

Description

Javascript Array myInject(func)


Array.prototype.myInject = function (func) {
  let accum = this[0];

  function action(el) {
    accum = func(accum, el);//from  w  w w  .ja  v  a2  s .  c o  m
  }

  this.slice(1).myEach(action);

  return accum;
};

// console.log([1,2,3].myInject((accum, el) => accum + el));

Javascript Array myInject(func)

//myInject//  w  w  w  .  j a  va  2  s  .co  m
Array.prototype.myInject = function(func) {
  var result;

  function injection(element) {
    if (typeof result === "undefined") {
      result = element;
    } else {
      result = func(result, element);
    }
  }

  this.myEach(injection);

  return result;
}



PreviousNext

Related