frontend-challenges icon indicating copy to clipboard operation
frontend-challenges copied to clipboard

82 - Array.prototype.reduce - javascript

Open jsartisan opened this issue 1 year ago • 0 comments

index.js

export const arrayReduce = (array, callback, initialValue) => {
  if (array == null) {
    throw new TypeError("arrayReduce called on null or undefined");
  }

  if (typeof callback !== "function") {
    throw new TypeError(callback + " is not a function");
  }

  let accumulator = initialValue;
  let startIndex = 0;

  if (accumulator === undefined) {
    if (array.length === 0) {
      throw new TypeError("Reduce of empty array with no initial value");
    }
    accumulator = array[0];
    startIndex = 1;
  }

  for (let i = startIndex; i < array.length; i++) {
    accumulator = callback(accumulator, array[i], i, array);
  }

  return accumulator;
};

jsartisan avatar Jun 18 '24 06:06 jsartisan