2018-04-28

How to Implement LINQ methods in JavaScript - Part 8

blogentry, programming, quicktip, series

banner

Photo by Pau Casals on Unsplash LINQ methods (All, Contains, SequenceEqual) in this article  are somehow related in a way that they are predicates (returns true or false).

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

🔴 Overview

In this article, I will cover following methods.

[table id=9 /]

The sample collections used in this part are shown as below.

C#

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

JavaScript

https://gist.github.com/dance2die/0f9c491d8f84f4b41084da4528df0cbb

🔴 Examples

🔸 All

JavaScript has a method called Array#every, which works the same way as All does.

https://gist.github.com/dance2die/00a33b12253b93fa4c6dfbfdb6559422

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

Results

https://gist.github.com/dance2die/039f61acb30978c45b9467a33d7cd4b4

every is more flexible as the callback is also passed an index.

array#every syntax

🔸 Contains

There are so many ways implement contains but i used some as it short circuits (returns as soon as a condition is met).

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

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

Results

https://gist.github.com/dance2die/939db3606e183efd3f4e697e2d1ad811

OrderEqualityComparer object instance simply checks if two objects are the same by an ID. JavaScript version simply passes a callback which does the same.

🔸 SequenceEqual

You can use every here to check if two sequences are the same as every passes an index of current element to the callback.

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

https://gist.github.com/dance2die/80b52df7f322e4281969c08494a8c26c

Results

https://gist.github.com/dance2die/0640e85a90be6d3b9e55cf8381c08850

🔴 Closing Remark

I hope this article can serve as a cheat sheet (that's how I started this series).

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.