FrontendChallenges is a collection of frontend interview questions and answers. It is designed to help you prepare for frontend interviews. It's free and open source.
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;
};
index.js