I do quite a lot of javascript and C# programming. Linq is one of the greatest things in C# and I was missing it in javascript, so I figured I could just implement what I needed. It took about one minute. Here is how I could improve  some of my code:

var a =[];
for (var i = 0; i < elements.length; i++) {
    a[a.length] = {
        name: elements[i].name,
        id: elements[i].id
    }
};
return a;

becomes

return elements.select(function(item) {
    return {
        Name: item.Name,
        Id: item.Id
    };
});

and

var res = [];
for (var i = 0; i < ids.length; i++) {
     for (var j = 0; j < this._currentList.length; j++) {
           if (ids[i] == this._currentList[j].Id)
               res[res.length] = this._currentList[j];
     }
}
return res;

becomes

return this._currentList.where(function(item) {
    return ids.contains(item.Id);
});


The actual implementation I call Blinq (e.g.) Bjarte Linq :p

if (Array.prototype.where != undefined)
    throw new Error("Duplicatte method definition on Array");

Array.prototype.where = function(match) {
    var a = [];
    for (var i = 0; i < this.length; i++) {
        if (match(this[i])) {
            a[a.length] = this[i];
        }
    }
    return a;
}

if (Array.prototype.select != undefined)
    throw new Error("Duplicatte method definition on Array");

Array.prototype.select = function(selection) {
    var a = [];
    for (var i = 0; i < this.length; i++) {
        a[a.length] = selection(this[i]);
    }
    return a;
}

if (Array.prototype.contains != undefined)
    throw new Error("Duplicatte method definition on Array");

Array.prototype.contains = function(obj) {
    var len = this.length;
    for (var i = 0; i < len; i++) {
        if (this[i] === obj) { return true; }
    }
    return false;
};

Not alot of code really.

Nitpickers corner: LINQ-like implementations of Javascript already exists, but when it takes me a minute to implement I don’t go about learning a new framework to get the job done :)

F Share