In ES5, the new array method reduce(). I am wondering if someone can explain more in depth.
The method you pass into .reduce
takes parameters previous_returned_value, current_iteration_item, current_iteration_index, context_array
This means that each time it is called, the first argument is the return
value from the previous invocation
The initial value is what is passed in only the very first time.
You can read the MDN docs about it here
return an object form which key is idx and value is Math.pow(idx,2)
e.g.
[1, 2, 3, 4, 5].reduce((o, e) => (o[e] = Math.pow(e, 2), o), {});
// Object {1: 1, 2: 4, 3: 9, 4: 16, 5: 25}
count how many letters are are in an array and turn it into the object
So again
['f', 'o', 'o', 'b', 'a', 'r'].reduce((o, e) => (o[e] = (o[e] || 0) + 1, o), {});
// Object {f: 1, o: 2, b: 1, a: 1, r: 1}
Please note the arrow notation functions I've used exploit the comma operator to return what I want, more traditionally you might write the function as e.g. followed by evolution to my examples
function (o, e) {
o[e] = Math.pow(e, 2);
return o;
}
// same as
function (o, e) {
return o[e] = Math.pow(e, 2), o;
}
// similar to
(o, e) => {
return o[e] = Math.pow(e, 2), o;
}
// same as
(o, e) => (o[e] = Math.pow(e, 2), o);