Javascript Array myInject(cb)

Description

Javascript Array myInject(cb)


Array.prototype.myInject = function (cb) {
  let accum = this[0];
  this.slice(1).myEach((el) => {/*from  ww  w . j  a  v a  2s  . c  o m*/
    accum = cb(accum, el);
  });
  return accum;
};

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


// console.log([1, 2, 3, 4].myInject ( function (accum, el) { return accum + el; }));

Javascript Array myInject(cb)

Array.prototype.myInject = function (cb) {
  let accumulator = this[0];

  this.slice(1).myEach((el) => {//  ww  w .  j  a v a  2s .  c om
    accumulator = cb(accumulator, el);
  });

  return accumulator;
};

let myInjectArray = [1,2,3,4,5];
console.log(myInjectArray.myInject((acc, el) => acc * el));



PreviousNext

Related