Implement Array.reduce

Array.reduce

The reduce() method executes a reducer function (that you provide) on each element of the array, resulting in a single output value.

Question

Implement the Array.reduce method

Thought process Pseudocode

  1. A function which takes a function as an argument and a starting value
  2. The reducer function, takes four parameters, an accumulator, a current value, index, the source array
  3. The starting value if passed, must be used as the initial accumulator, if no accumulator is passed then the first element of the array becomes the first element itself
  4. The execution context of the callback becomes that of the accumulator.

Solution

/**
* Reduce function is attached to the array prototype
* It takes in a callback and passes every item, along with accumulator in the array
* through the callback, and also a starting value
*/
/**
* The callback gets 4 arguments
* an accumulator, current value, index, current array
*
*/
Array.prototype.newReduce = function (callback, startingValue) {
// as starting value is an optional param
// make a check
let accumulator = startingValue || undefined;
for (let index = 0; index < this.length; index++) {
if (accumulator) {
accumulator = callback.call(accumulator, accumulator, this[index], index, this)
} else {
accumulator = this[index]
}
}
return accumulator;
}
const nums = [1, 2, 3, 4, 5]
const double = nums.newReduce((accum, current) => {
accum.push(current * 2)
return accum
}, []);
console.log(double)
const queryString = "cat=meow&duck=quack&dog=woof";
const queryObject = queryString.split("&").newReduce((accum, current) => {
const splitString = current.split("=")
accum[splitString[0]] = splitString[1];
return accum;
}, {})
console.log(queryObject);

Caveat

Only the accumulator and the current value are mandatory parameters in the callback function, the initial value as seen above is optional. Calling reduce() on an empty array without an initialValue will throw a TypeError. This method is useful if you want to transform the elements in an array into a single entity. The reduce can be used to implement the Array.map and Array.reduce method.