/**
 * reduce() 関数を使用して
 * 配列の全要素を足し合わせ、累計された一つの値を生成する例
 */

// reduce() 関数を適用する配列
const numbers = [1, 2, 3, 4, 5];

// 開発者が直接作成したコールバック関数
function sum(total, number) {
    // 以前の結果値と現在の要素を足します。
    return total + number;
}

// 配列の全要素にコールバック関数を適用し、集計した一つの結果値を返す
const result = numbers.reduce(sum);
console.log(result); // 出力: 15
arr.reduce(callbackFn[, initialValue])
// アロー関数 (Arrow function)
reduce((accumulator) => { /* … */ })
reduce((accumulator, currentValue) => { /* … */ })
reduce((accumulator, currentValue, currentIndex, array) => { /* … */ })
reduce((accumulator, currentValue, currentIndex, array) => { /* … */ }, initialValue)

// コールバック関数 (Callback function)
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]])
/**
 * コールバック関数
 *
 * コールバック関数は、名前付き関数(ユーザー定義関数)や匿名関数などで使用できます。
 * (当然ながら)すべてのコールバック関数はアロー関数として使用可能です。
 */

/* コールバック関数に名前付き関数を使用する場合 */
function callbackFn(accumulator, currentValue, currentIndex, array) { // 名前付き関数の定義
    // 単一の値を生成するロジック:累積された結果を返す必要があります。
}

arr.reduce(callbackFn); // 定義した名前付き関数名を引数に直接渡す

/* コールバック関数に匿名関数を使用する場合 */
arr.reduce(function (accumulator, currentValue, currentIndex, array) {
    // 単一の値を生成するロジック:累積された結果を返す必要があります。
});
const numbers = [1, 2, 3, 4, 5];

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

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

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

const result = numbers.reduce(sum, 1);
console.log(result); // 出力: 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); // 出力: 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); // 出力: 9
const numbers = [1, 2, 3, 4, 5];

const square = (accumulator, currentValue) => {
    // 現在の要素の二乗値を計算して配列に追加
    accumulator.push(currentValue * currentValue);
    return accumulator; // 累積された配列を返却
}

const squaredArray = numbers.reduce(square, []);

console.log(squaredArray); // 出力: [1, 4, 9, 16, 25]
const numbers = [1, 2, 3, 4, 5];

const square = (currentValue) => {
    return currentValue * currentValue;
}

const squaredArray = numbers.map(square);

console.log(squaredArray); // 出力: [1, 4, 9, 16, 25]