4 ms·
How would you abuse reduce()?
by WirelessGigabit 3y ago
How would you abuse reduce()?
- Too 3y agoMDN even had to make a whole chapter to discourage overuse of it. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/Reduce#when_to_not_use_reduce https://developer.mozilla.org/en-US/docs/Web/JavaScript/Refe...
- masklinn 3y agoUsing reduce to perform a map is a fun way to annoy colleagues.
- 5e92cb50239222b 3y agoOr .map() as a for..of replacement. I always wanted V8/SpiderMonkey developers to make .map()/.reduce() "pure" in the sense of "optimizing away" the expression if its result is not assigned to anything, and see the world burn.
- Zababa 3y agoI think .map() as a for...of replacement makes sense for simple cases. newArray = oldArray.map(el => aFunction(el)) is short, sweet and clean.
- orra 3y agoIt's definitely short, but are you doing it for the side effects? Then I find .map() misleading. I'd much prefer a .forEach(), or a for...of.
- masklinn 3y agoIf you’re mapping for side effects you deserve a good rap on the head. The main value of “map” is to denote a 1:1 data transformation. Plus this gets very fraught with many langages mapping lazily, and some not guaranteeing the order of operation.
- pwdisswordfishc 3y agoUse it at all, presumably.
- JuanPosadas 3y agoI'm probably on the mild side of abusing it, I've never seen another developer on my team use it, but I also include self-describing variables for the values. If the reducer function itself is non-trivial, I've give it a name so the final product may look like: const idNameMap = itemList.reduce(toIdNameMap) It should be intuitive that itemList is a list of objects familiar to the context of the code, and the result will be like: [{"id1":"Billy"}, etc.
- masklinn 3y agoIt’s really not clear to me what the transformation is, but from the naming and result it mostly looks like it’s an abuse of reduce and should be a map, possibly feeding into an Object / Map constructor / factory?
- yakshaving_jgt 3y ago> It should be intuitive that itemList is a list of objects …But how?! I can't see how anyone could build an intuition for this opaque line and the example of its apparent result. It's confusing enough that `idNameMap` actually refers to a list (or array), and not a map (or object).