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.

【JavaScript】forEachよりもreduceのほうが万能性高くない?

Posted at

forEach の模倣

次のようなforEachは、

forEach.js
array.forEach(body);

reduceにより一行で模倣できる。

simulation_forEach.js
array.reduce((_, ...args) => void body(...args), void 0);

reduce の模倣

逆に、次のようなreduceも、

reduce.js
const result1 = array.reduce(reducer, init);

forEachにより模倣できる。ただし、一行では模倣できない。

simulation_reduce.js
let acc = init;
array.forEach((...args) => {acc = reducer(acc, ...args)});
const result2 = acc;

用法用量を守って畳み込みましょう

forEachは万能だけど、reduceはそれにもまして万能なので、気をつけて使わないとやたら抽象的なコードになったりする。
reduceを使うときは「他のメソッドで代替できないか」、「forwhileで書いたほうがわかりやすくないか」、一度立ち止まって考えたい。

0
0
6

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?