As I was working with .NET, I started wondering how I would implement the LINQ methods syntax in Javascript. So here is my first try; is there a more elegant, or more performant, way to write this code?
// usage : the functions take a predicate function as input and modify the array accordingly
var collection;
(function() {
"use strict";
var Collections = function(array) {
this.array = array;
};
Collections.prototype = {
//The predicate should return a boolean value
//Keeps all elements that match the given function
where: function(predicate) {
var newArray = [];
this.each(function(index, item) {
if (predicate(item)) {
newArray.push(item);
}
});
this.array = newArray;
return this;
},
//The predicate should return a boolean value
//Returns true if one element or more matches the predicate
any: function(predicate) {
var newArray = [];
this.each(function(index, item) {
if (predicate(item)) {
newArray.push(item);
}
});
return newArray.length > 0;
},
//The predicate should return an object
//Replaces all elements by the object generated by the predicate
select: function(predicate) {
var newArray = [];
this.each(function(index, item) {
newArray.push(predicate(item));
});
this.array = newArray;
return this;
},
//Returns the current (modified) array
getArray: function() {
return this.array;
}
};
collection = function(array) {
return new Collections(array);
};
} ());
And here is an exemple of use:
var myArray = [{name: 'chicken', size: 1}, {name: 'cat', size: 2},
{name: 'dog', size: 3}, {name: 'horse', size: 4}, {name: 'skunk', size: 2}];
var newArray = collection(myArray)
.where(function(animal){
return animal.size == 2
})
.select(function(animal){
return {
animalName: animal.name,
category: 'mammal',
size: 'small'
}
})
.getArray()
// new array : [{animalName: 'cat', category: 'mammal', size: 'small}, {animalName: 'skunk',
// category: 'mammal', size: 'small'}]