Introduction
This code extends Arrays in JavaScript, adding the main domain and filtering functions of LINQ, Count()
, First()
, Exists() and Where()
.
Background
By using the JQuery function grep and prototype, it's possible to extend Array
class and simulate basic LINQ functions.
Sample:
myArray.Count("['name']=='luis'")
As shown above in the sample, all functions have the same format.
stringObject.FunctionName(stringFilter)
stringFilter
may be a complex logic sentence, functions will execute by using eval
functions.
The code is very easy to understand, as shown below.
Using the Code
JavaScript Code
var myArray = [
{ id: 1, name: "luis", checked: false }
, { id: 2, name: "juan", checked: true }
, { id: 3, name: "ana", checked: false }
];
function itemParser(str) {
var result;
result = str.replace(/item/gi, "");
result = result.replace(/\[/g, "item[");
return result;
}
Array.prototype.Count = function (expr) {
if (expr == null || expr == "") return this.length;
return ($.grep(this, function (item, index) {
return (eval(itemParser(expr)));
}).length);
};
Array.prototype.First = function (expr) {
if (expr == null || expr == "") expr = "true";
var result = ($.grep(this, function (item, index) {
return (eval(itemParser(expr)));
}));
return (result.length > 0 ? result[0] : null);
};
Array.prototype.Exists = function (expr) {
if (expr == null || expr == "") expr = true;
var result = ($.grep(this, function (item, index) {
return (eval(itemParser(expr)));
}));
return (result.length > 0);
};
Array.prototype.Where = function (expr) {
return ($.grep(this, function (item, index) {
return (eval(itemParser(expr)));
}));
};