0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

Array.prototype.reduce() の動作確認メモ

Last updated at Posted at 2021-08-08

引数が Reducer のみの場合 ~ reduce(reducer) ~

arrayの要素数(n) reducerの実行回数 備考
n == 0 - ❌ エラーがスローされる
n == 1 n-1 (0) reducerは実効されず、reduceの戻り値は array[0] となる
n >= 2 n-1 n == 2 の場合、引数array[0], array[1]で 1 回実行される

初期値も与えられている場合 ~ reduce(reducer, initialValue) ~

arrayの要素数(n) reducerの実行回数 備考
n == 0 n (0) reducerは実効されず、reduceの戻り値は initialValue となる
n == 1 n reducerは 引数initialValue, array[0]で 1 回実行される
n >= 2 n reducerは n 回実行される

補足

以下の式はtrueとなる

[initialValue, ...array].reduce(reducer) === array.reduce(reducer, initialValue)

検証用スニペット1

const h1 = (msg) => console.group(`%c${msg}`, `font-size: 1.5em;`);
const h2 = (msg) => console.group(`%c${msg}`, `font-size: 1.2em;`);
const countKey = "execute reducer"; let reducerの実行回数 = 0;
const reducer = (acc, val)=> {
  console.count(countKey); reducerの実行回数++;
  console.log({acc,val});
  return "accumulator";
}
const 検証 = (...reducerArgs) => (array) => {
  h2(`${JSON.stringify(array)} を検証`);
  let reduceの戻り値;
  try {
    reduceの戻り値 = array.reduce(...reducerArgs);  
  } catch(e) { console.error(e); }
  console.table({arrayの要素数: array.length, reducerの実行回数, reduceの戻り値})
  console.countReset(countKey); reducerの実行回数 = 0;
  console.groupEnd();
}
const a0 = "array[0]", a1 = "array[1]"

h1("引数が Reducer のみの場合");
const reducerのみの場合を検証 = 検証(reducer)
reducerのみの場合を検証([]);
reducerのみの場合を検証([a0]);
reducerのみの場合を検証([a0,a1]);
console.groupEnd();

h1("初期値も与えられている場合");
const 初期値ありの場合を検証 = 検証(reducer, "initialValue");
初期値ありの場合を検証([]);
初期値ありの場合を検証([a0]);
初期値ありの場合を検証([a0,a1]);
console.groupEnd();

検証用スニペット2

const reducer = (a, b) => `${a} + ${b}`;
const initialValue = 1, array = [2,3];
console.assert([initialValue, ...array].reduce(reducer) === "1 + 2 + 3");
console.assert([initialValue, ...array].reduce(reducer)
                              === array.reduce(reducer, initialValue));

console.assert([1].reduce(reducer) === [].reduce(reducer,1));
console.assert([1,2].reduce(reducer) === [2].reduce(reducer,1));
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?