Javascript Linq Extensions

I love Linq. Linq just makes code awesome. Well, that’s my view on it anyway. I also like Javascript, and through libraries like JQuery we’ve now got a framework whereby you can pretty much do anything, but often I like getting down to the bare-bones of Javascript and just having a go at what it can do.

One of the great things about Javascript objects is that they are so easy to extend. This is due to the prototyping nature of the language itself. Recently on my journey on Stack Overflow (~1200 in 22 days!) a question was asked about searching through a javascript array for a specific item. Of course we could easily do something like this:

for (var i = 0; i < arrayObj.length; i++) { … }
…etc, but I remembered a while ago I had written some very cool Linq-esque style extension methods to Javascript array object. Methods like Where, Select, etc, here’s an example of my Where method:

Array.prototype.Where = function(predicate) {
Throw.IfArgumentNull(predicate, “predicate”);
Throw.IfNotAFunction(predicate, “predicate”);

var results = new Array(); for (var i = 0; i < this.length; i++) { var item = this[i]; if (predicate(item)) results.push(item); } return results;
Code language: JavaScript (javascript)

};
Given that, I could do something like so:

Person = function(name, age, likes) {
this.Name = name;
this.Age = age;
this.Likes = likes;
};

var people = new Person(“Doug”, 20, “Bananas”), new Person(“Jeff”, 21, “Apples”), new Person(“Richard”, 22, “Oranges”), new Person(“Bonzo”, 50, “Bananas”) ;

var peopleWhoLikeBananas = people.Where(function(p) {
return (p.Likes == “Bananas”); });
Pretty cool eh? If you’re familiar with the Linq extension methods, you should be at home here too!

I also decided to extend the base Object class itself, providing some Equals and CompareTo methods that act as default equality and comparer methods:

Object.Equals = function(objA, objB) {
if (objA != null)
return objA.Equals(objB);

if (objB != null) return objB.Equals(objA); return false;
Code language: JavaScript (javascript)

};

Object.prototype.CompareTo = function(object) {
if (this < object)
return -1;

if (this > object) return 1; return 0;
Code language: JavaScript (javascript)

};

Object.prototype.Equals = function(object) {
return (this == object);
};
Also included in the attached zip is my prototype Javascript testing framework and also the micro-mocking framework I blogged about previously, it’s nothing special and nowhere near production code:

Attached in a zip of all the bits and bobs, its nothing formal and it’s not production code, do with it what you will. I appreciate any feedback too.

Javascript-Linq-Extensions

Leave a Reply

Your email address will not be published.

Related Post