Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- function reduce(list, callback, initialValue) {
- if (list == null || !Array.isArray(list)) {
- throw new TypeError("list is not a valid array");
- }
- if (typeof callback !== "function") {
- throw new TypeError(callback + " is not a function");
- }
- if (initialValue === undefined && list.length === 0) {
- throw new TypeError("Reduce of empty array with no initial value");
- }
- let accumulator = initialValue;
- for (let currentIndex = 0; currentIndex < list.length; currentIndex++) {
- currentValue = list[currentIndex];
- accumulator = callback(accumulator, currentValue, currentIndex, list);
- }
- return accumulator;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement