2018-04-21

How to Implement LINQ methods in JavaScript - Part 7

blogentry, programming, quicktip, series

banner

Photo by rawpixel.com on Unsplash I will cover LINQ methods for initializing a sequence.

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=8 /]

I won't be using Orders collections as I have in previous articles.

🔴 Examples

🔸 Empty

C# is a typed language while JavaScript is not. .Empty returns a typed sequence but since there is no need for a type, you can just return an empty array [] in JavaScript

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

https://gist.github.com/dance2die/13d4e1b43584e8420c7afbd3af3fc624

Results

https://gist.github.com/dance2die/3191e9817d277fda821bc62c90f7ac5c

Nothing surprising as shown above 😀.

🔸 Repeat

For this demo, I thought it was an overkill to use Orders collection used in last 6 articles so simply repeated a sentence, "I love your smile" five times.

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

https://gist.github.com/dance2die/46fba8b00962893de1b8976d7d1d32b0

Results

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

JavaScript version uses Array#fill method to simply fill it with undefined and populate it with map.

🔸 Range

Same here with the Repeat Demo, I will use a simple case to demo how to generate a range of numbers.

https://gist.github.com/dance2die/526bcddc2779116e299595b8e36aa463

https://gist.github.com/dance2die/042c3f009b4836d3673fe385f0976321

Results

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

I used he same technique but utilizing an index property of map callback, which is where initialization of a range occurs (index starts from 0).

🔴 Closing Remark

If you have been following the series, you might have noticed that many JavaScript implementations uses map and reduce.

It's because many LINQ methods are simply a syntactic sugar over what "map" and "reduce" can do.

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.