让我们把它分解成组成部分
const foo = countsMap.get(item); // get the value of key `item` from a Map
const bar = foo + 1 || 1; // Increment foo by 1, or start at 1
// n.b. this works because `undefined + 1; // NaN`, I would instead
// recommend `(foo || 0) + 1`
const baz = countsMap.set(item, bar); // set the value of key `item` to `bar`
// n.b. this is chainable (i.e. returns `countsMap`)
const fn = (x, y) => x + y; // a function which takes x and y, and returns their sum
// so finally,
const reducor = (countsMap, item) => countsMap.set(item, countsMap.get(item) + 1 || 1);
// 1. look up from map
// 2. increment 1, or start at 1
// 3. set back to map
// 4. return map
Array.prototype.reduce
我发现向某人表达这一点的最简单方法是手写
const arr = [1, 2, 3]; // some array
const sum = (accumilator, nextValue) => accumilator + nextValue; // some function
// n.b. the return value is the next accumilator
const initialValue = 0;
const result = arr.reduce(sum, initialValue); // 6, i.e. 1 + 2 + 3
那么这看起来像普通话,例如在 for 循环中?
// lets start the same as before
const arr = [1, 2, 3];
const sum = (accumilator, nextValue) => accumilator + nextValue;
// now to calculate the result,
let accumilator = 0; // = initial value
for (let i = 0; i < arr.length; ++i) {
const nextValue = arr[i];
accumilator = sum(accumilator, nextValue);
}
accumilator; // 6