2018-03-31

How to Implement LINQ methods in JavaScript - Part 5

blogentry, programming, quicktip, series

banner

Photo by Jonas Vincent on Unsplash

I will cover common number aggregate methods in this article.

Here are the methods covered so far.

  1. Part 1 〰️ Select, Aggregate, Where, OrderBy (Ascending, Descending)
  2. Part 2 〰️ Any, Distinct, Concat, SelectMany
  3. Part 3 〰️ Reverse, Zip, Min/Max
  4. Part 4 〰️ Union, Intersect, Except
  5. Part 5 〰️ Sum, Average, Count
  6. Part 6 〰️ First, Last, DefaultIfEmpty, Skip, Take
  7. Part 7 〰️ Empty, Repeat, Range
  8. Part 8 〰️ All, Contains, SequenceEqual

I've covered "min" and "max" in part 3 so I won't cover them again here.

🔴 Overview

In this article, I will cover following methods.

[table id=5 /]

And I will try to stick to using VanillaJS as I have so far.

The sample collections used in this article.

C#

https://gist.github.com/dance2die/91eccd44af4248a07ca031c7cb97c1d5

JavaScript

https://gist.github.com/dance2die/8ddcdfd02c4dc710d16cc71875a748c5

🔴 Examples

🔸 Sum

I will show you "Sum" demo first since "Average" is basically a sum divided by count.

https://gist.github.com/dance2die/6a39ea12bc4253c0eda08f456162650b

https://gist.github.com/dance2die/10f4e530b7cc145d84c9efa5cf4f2134

Results

https://gist.github.com/dance2die/8257620ec4b39b0fc4ad8de1c6b50717

Array.prototype.sum simply reduces each order quantity by summing it in the callback. Note 📝: It's exactly the same as the reduceDemo.

🔸 Average

Now let's get an average quantity ordered.

https://gist.github.com/dance2die/3a50fa4e91997ac7518f2a55f0332992

https://gist.github.com/dance2die/0013a7255e993ac11914e663799fd8c8

Results

https://gist.github.com/dance2die/8d5c5e20e7a453004eda71053bbd1bba

The only difference here is that sum is divided by the order count to calculate an average.

🔸 Count

Count is overloaded in LINQ; One that simply returns a number of element in a sequence, and the other that accepts a predicate which lets you test each item.

I will implement the one with the predicate as the former is too simple.

https://gist.github.com/dance2die/e625943d0df70bfcf2248edbd220e187

https://gist.github.com/dance2die/a33e3a0fbad62840fdba9ad70260aef1

Results

https://gist.github.com/dance2die/8910c67f5533f20b747f191ae34e0793

The demo counts number of orders placed on and after March of 2018. Count without a predicate is same as array.length but filter is required for testing each element in an array.

🔴 Closing Remark

Sum, Average, and Count are often used and easy to implement (using for/each loops). I used reduce and filter to implement to make it look as similar to LINQ methods.

As always, I've not tested edge cases for Array prototypes so use the code at your own risk 😃. Please let me know should you find any errors or improvements I can make to the codes.

The full source code and instructions on how to run them are on GitHub.