patternjavascriptMinor
Code review for a collection manipulation tool in Javascript
Viewed 0 times
javascriptcollectionmanipulationforcodereviewtool
Problem
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?
And here is an exemple of use:
```
var myArray = [{name: 'chicken', size: 1}, {name: 'cat', size: 2},
{name: 'dog', size: 3}, {name: 'horse
// 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
Solution
To clarify the use of your global variable "collection" as a namespace for your library, you should assign it directly to a value returned by your Immediately Invoked Function Expression:
var collection = (function(){
...
function collection(array) {
return new Collections(array);
}
return collection;
}());Code Snippets
var collection = (function(){
...
function collection(array) {
return new Collections(array);
}
return collection;
}());Context
StackExchange Code Review Q#16400, answer score: 2
Revisions (0)
No revisions yet.