Posts

Showing posts from March, 2024

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