A while ago, I posted a question on StackOverflow showing that the native implementation of reduceRight in JavaScript is annoying. Hence, I created a Haskell-style foldr function as a remedy:
function foldr(array, callback, initial) {
var length = array.length;
if (arguments.length < 3) {
if (length > 0) var result = array[--length];
else throw new Error("Reduce of empty array with no initial value");
} else var result = initial;
while (length > 0) {
var index = --length;
result = callback(array[index], result, index, array);
}
return result;
}
However, I never used this foldr function simply because I never needed to iterate over an array from right-to-left. This got me thinking, why don't I use foldr in JavaScript as much as I do in Haskell and what are some real world examples of using foldr in JavaScript?
I could be wrong, but I believe that the foldr function is used widely in Haskell because of:
- Lazy Evaluation (foldl is tail recursive, so how come foldr runs faster than foldl?)
- Short cut fusion using
foldr/build(Correctness of short cut fusion:foldr/build)
This would explain why foldr or reduceRight are not widely used in JavaScript. I have yet to see a real world use of foldr only for its right-to-left iteration order.
This brings me to my two questions:
- What are some real world examples of using
reduceRightin JavaScript? Perhaps you have used it in an npm package. It would be great if you could link me to your code and explain why you needed to usereduceRightinstead ofreduce. - Why is
reduceRightnot used as widely asreduceis in JavaScript? I already provided my two cents on this matter. I believe thatfoldris primarily used only for its laziness, which is whyreduceRightis not very useful in JavaScript. However, I could be wrong.
For the first question, I tried to find some real world examples for using reduceRight in JavaScript. However, I didn't find any satisfactory answers. The only examples I found were trivial and theoretical:
when to use reduce and reduceRight?
What I am looking for is a practical example. When is it practical to use reduceRight in JavaScript instead of reduce?
For the second question, I understand that it is primarily opinion based which is why it's alright if you don't answer it. The main focus of this post is on the first question, not the second.