3 ms·
The example with the promises, if I read it correctly, is basically using reduce as an alternative way to do a for loop. One of the easiest ways to tell that i
by thawaway1837 7y ago
The example with the promises, if I read it correctly, is basically using reduce as an alternative way to do a for loop.
One of the easiest ways to tell that it’s a misuse of reduce is that the result is not being assigned to anything.
The times I use reduce are simple. I want to “reduce” a collection of some sort to a single value, without any side effects. It’s additionally beneficial if the action being performed can be encapsulated in a function, so I can simply pass the function in, instead of code. However, this isn’t necessary.
JS doesn’t enforce it, but the code my team and I write requires that reduce has no side effects (we enforce through code review).
The point is that when I come across reduce in our team’s code, the intention is communicated to me immediately. A collection of some sort was converted to a single value, and there were no side effects.
That won’t be my expectation if it’s a for loop, or a forEach, or a while.
If those conditions are not met for a reduce, then it’s a bug in the code, as far as my team is concerned.
- WorldMaker 7y ago> The example with the promises, if I read it correctly, is basically using reduce as an alternative way to do a for loop. > One of the easiest ways to tell that it’s a misuse of reduce is that the result is not being assigned to anything. The example with Promises is using the accumulator, it's just referring to it as "sequence" to more accurately describe what it using the accumulator for (to "sequence" in serial a set of Promises). While the final result from the accumulator isn't assigned to anything in snippet as shown, one would easily imagine it being used as a "finished loading all of the chapters" promise before some other action. It would definitely be a better example if the side effect (`addHtmlToPage`) wasn't performed inside the promise callbacks but on the results, but it's still an alright example of promise composition. Though reduce for promise composition isn't a great example today when most cases these days you'd just want to write it async/await and a traditional for loop, with the browser or your transpiler doing the composition work for you, leaving it a clearer to read sequence of events.