Lack of clear alternative for reduceRight in unicorn/no-array-reduce
See original GitHub issueI do not wish to re-litigate #623 but I am here as the rule triggered for Array#reduceRight
after updating xo.
For Array#reduce
there is a clear alternative which is to use a for (const ... of array) { ... }
loop.
However, there is no clean way to iterate over an Array backwards, the best I can come up with is for (let i = array.length - 1; i >= 0; i--) { const ... = array[i]; ... }
but in my (admittedly subjective) opinion having to use indicies is worse than the complexity introduced by reverseRight.
Rule: unicorn/no-array-reduce
The code in question looks a bit like:
const listEmpty = null;
const listCons = (element, list) => ({
head: element,
tail: list,
});
const listFromArray = (array) =>
array.reduceRight((list, element) => listCons(element, list), listEmpty);
And I think that (the best alternative that I can think of)
const listFromArray = (array) => {
let list = listEmpty;
for (let i = array.length - 1; i >= 0; i--) {
const element = array[i];
list = listCons(element, list);
}
return list;
}
is worse because of how easy it is to make an off-by-one error with the indexing logic.
I am happy to (and have) used a splash of eslint-disable-next-line
so happy for this to be closed but I thought it is worth sharing.
Of course it is possible that there is a much nicer way to iterated backwards over an array that I have missed. If there is it would be great to add it to the docs for unicorn/no-array-reduce which currently do not show an alternative for reduceRight
.
Issue Analytics
- State:
- Created 3 years ago
- Reactions:2
- Comments:9 (2 by maintainers)
Top GitHub Comments
I am not a maintainer of this repo but for what I know of @sindresorhus I’m pretty sure a PR would be very welcome, and I guess @fisker would agree 😃
The reverse method is nice but I don’t have the motivation to benchmark it (even v8 isn’t that smart is it?).
I think its easier to add the eslint-disable than the helper function in my case (my case is unusually function programming style for js so is probably uniquely suited to a reduce) but I agree it is probably the best of both worlds solution. Would a PR adding it to the docs be welcome?