0
Could someone please explain the following ES6 code?
function magic(...nums) { let sum = 0; nums.filter(n => n % 2 == 0).map(el => sum+= el); return sum; }
2 ответов
+ 5
-magic(...nums) <==> indefinite number of parameters to a function and access them in an array.
-filter(n => n % 2 == 0) <==> creates a new array with all el that passes the test implemented by the provided function.
-map(el => sum += el) <==> creates a new array populated with the results of calling a provided function on every el in the calling array.
+ 1
ES6 allow you to do the same behavior (returning sum of even numbers from passed ones as arguments) with a single line/loop (technically filter do one loop, and map do another one), and avoiding two temporary arrays creation:
const magic = (...nums) => nums.reduce((r,v) => v%2 ? r : r + v,0);