/**
 * Example of using reduce() 
 * to sum all elements of an array and produce a single accumulated value
 */

// Array to apply reduce() on
const numbers = [1, 2, 3, 4, 5];

// Callback function written by the developer
function sum(total, number) {
	// Add the previous accumulated value and the current element
	return total + number;
}

// Apply the callback function to all elements and return the single result
const result = numbers.reduce(sum);
console.log(result); // Output: 15
arr.reduce(callbackFn[, initialValue])
// Arrow function
reduce((accumulator) => { /* … */ })
reduce((accumulator[, currentValue]) => { /* … */ })
reduce((accumulator[, currentValue[, currentIndex[, array]]]) => { /* … */ })

// Callback function reference
reduce(callbackFn)
reduce(callbackFn[, initialValue])

// Inline callback function
reduce(function (accumulator) { /* … */ })
reduce(function (accumulator[, currentValue]) { /* … */ })
reduce(function (accumulator[, currentValue[, currentIndex[, array]]]) { /* … */ })
reduce(function (accumulator[, currentValue[, currentIndex[, array]]]) { /* … */ }[, initialValue])
callbackFn(accumulator, currentValue[, currentIndex[, array]])
/**
 * Callback Function
 *
 * The callback function can be a named function (user-defined) or an anonymous function.
 * Naturally, you can also use an arrow function for the callback.
 */

/* Using a named function as a callback */
function callbackFn(accumulator, currentValue[, currentIndex[, array]]) { // Named function definition
    // Logic to accumulate a single value: must return the updated result
}

arr.reduce(callbackFn); // Pass the named function directly as an argument

/* Using an anonymous function as a callback */
arr.reduce(function(accumulator, currentValue[, currentIndex[, array]]) {
    // Logic to accumulate a single value: must return the updated result
});
const numbers = [1, 2, 3, 4, 5];

const sum = (total, number) => {
	return total + number;
}

const result = numbers.reduce(sum);
console.log(result); // Output: 15
const numbers = [2, 3, 4, 5];

const sum = (total, number) => {
	return total * number;
}

const result = numbers.reduce(sum, 1);
console.log(result); // Output: 120
const numbers = [5, 3, 9, 2, 7];

const min = (min, item) => {
    return (item < min) ? item : min;
}

const result = numbers.reduce(min, numbers[0]);
console.log(result); // Output: 2
const numbers = [5, 3, 9, 2, 7];

const max = (max, item) => {
    return (item > max) ? item : max;
}

const result = numbers.reduce(max, numbers[0]);
console.log(result); // Output: 9