Write javascript polyfill for array.reduce

 


// Example: Predefined Array.reduce

// let arr = [1,2] 

// arr.reduce((total, current) => total, initialvalue)

// let newArr = arr.reduce((total, current) => total + current,  0)

// console.log('hello new: ', newArr)


/* Polyfill for reduce */

function myreduce(cb, init) {

let copyArr = this;  

  let arrLen = copyArr.length;

  

  // output

  let acc = init;

  

  // traverse right to left

  while(arrLen) {

  let currItem = copyArr[arrLen - 1];

  acc = cb(acc, currItem);

    arrLen--;

  }

  return acc;

}

Array.prototype.myreduce = myreduce;

console.log('Polyfill: ', [1, 2].myreduce((total, current) => total + current,  0));

// Output: 3

Comments

Popular posts from this blog

Abhijit Padhy

Find the longest substring in a given string.

Find the robot matching the given query having [top, right, bottom, left] index of the nearest walls in a 2D array.