LINQ in JavaScript, now with more ES5

Sunday, Feb 6, 2011 2 minute read Tags: javascript linq web linq-in-javascript
Hey, thanks for the interest in this post, but just letting you know that it is over 3 years old, so the content in here may not be accurate.

When I first wrote LINQ in JavaScript a few years ago it was just a thought experiment.

Since then I’ve actually found that I want to use it, quite often in fact, and a lot of the reason I’ve been wanting this is because I’m lacking the ECMAScript 5 features which LINQ in JavaScript provides.

ECMAScript 5 quick primer

A lot of people mistake many of the ECMAScript 5 (ES5) features for being HTML5, but it isn’t really, what we’re looking at here are the next features of JavaScript, and these are the map/filter methods.

These methods are similar to the kind of things you expect in functional programming languages, and how you can interact with arrays. The IE9 Test Drive actually has a good set of examples of using these new features.

So now that browsers are starting to come with built in methods like Array.prototype.map, which will transform the data into a new type or Array.prototype.filter, allowing us to conditionally remove items from the array, it’d make sense to actually use them.

Improving LINQ in JavaScript

As I said browsers are starting to ship with the new features on Array they are going to be a lot faster than anything written purely in JavaScript and residing in-browser.

Let’s for example look at improving the Array.where method:

Array.prototype.where = Array.prototype.filter || function (fn) {
	//implement a custom method
}

Here what we’re doing is executing the logic of:

  • If the Array.prototype.filter method exists assign it to Array.prototype.where
  • If it doesn’t we’ll provide a custom method

We can do the same thing with select and indexOf, using built-in methods from the Array.prototype chain.

Other updates

While adding these updates I also decided to do some other performance tweaks:

  • skip will now use Array.prototype.slice rather than iterating through the collection in JavaScript
  • take also uses slice, but does a -1 multiplication so we go backwards through the collection
  • groupBy has been cleaned up so there’s a few less lines of code in it
  • select and where will pass in all the ES5 arguments when running in browsers that don’t support ES5

Feel free to check out the code from my bitbucket, and maybe some others than I will use it ;).