Watch: https://youtu.be/X85QdHe1tDw?t=409 (Starts at 6:50)
reduce
is one of the least understood Array
methods, and probably the most abused.
Reducing, as the good functional programmer intended:
let total = arr.reduce(function (acc, el) {
return acc + el;
}, 0);
Subtle difference (read: bug) in JavaScript:
let total = arr.reduce(function (acc, el) {
return acc + el;
});
(when the initial value is omitted, the first array element is used)
await arr.reduce(async function (promise, fn) {
await promise;
await fn();
}, Promise.resolve())
Which is the same as this:
let p = Promise.resolve();
arr.forEach(function (fn) {
p = p.then(function () {
return fn();
});
});
await p;
Which is the same as this:
Promise.resolve()
.then(function () {
var fn = arr[0];
return fn();
})
.then(function () {
var fn = arr[1];
return fn();
})
.then(function () {
var fn = arr[2];
return fn();
})
.then(function () {
var fn = arr[...];
return fn();
})
Promise.all()
will run in parallel (all-at-once), not in sequence (one-after-the-other).
reduce
can be a sort of inverse of map
.
You can use map
to create arrays from arrays or objects:
arr.map(function (el) {
// ...
})
let arr = Object.keys(hashmap).map(function (k) {
let val = hashmap[k];
val.name = k;
return val;
});
You can use reduce
to create objects from objects or arrays:
let obj = arr.reduce(function (obj, el) {
obj[el.name] = el;
return obj;
}, {});
However, forEach
is easier to read and reason about:
let obj = {};
arr.forEach(function (el) {
obj[el.name] = el;
});