I've written two Array methods that I think will be pretty useful for the work I'm doing. Modeled after Ruby's array methods, here are my find and find_all methods. Just thought I'd toss them to the community and get some feedback. I'm pretty new to JS programming so I'm probably not using enough defensive mechanisms and maybe there are some optimizations to be made. Any thoughts?
Array.prototype.find = function(attrs){
// If an object wasn't passed in return false, maybe throw format exception?
// or do primitive type search, but that's not really useful as you're passing in the very value you're looking for
if (typeof attrs != 'object'){
return false;
}else{
for(var i=0; i < this.length; i++){
if (typeof this[i] != 'object'){
return false;
}else{
var match = true;
// Loop through all attributes of the parameters object and test for existence and match
for(item in attrs){
match = match && (this[i][item] && (this[i][item] === attrs[item]) );
}
if(match){
return this[i];
}
}
}
// default return if no items found
return false;
}
};
// find_all behaves similarly to find only returns all matched objects
// See ruby's find_all method on arrays
Array.prototype.find_all = function(attrs){
// If an object wasn't passed in return false, maybe throw format exception?
// or do primitive type search, but that's not really useful as you're passing in the very value you're looking for
if (typeof attrs != 'object'){
return false;
}else{
var valid_items = [];
for(var i=0; i < this.length; i++){
if (typeof this[i] != 'object'){
return false;
}else{
var match = true;
// Loop through all attributes of the parameters object and test for existence and match
for(item in attrs){
match = match && (this[i][item] && (this[i][item] === attrs[item]) );
}
if(match){
valid_items.push(this[i]);
}
}
}
return valid_items;
}
}
Some examples:
var a={id:1,parent_id:2}
var b={id:2,parent_id:3}
var c={id:3,parent_id:2}
var arr = [a,b,c]
arr.find({parent_id:2})
// Object id: 1 parent_id: 2
arr.find_all({parent_id:2})
// [Object id: 1 parent_id: 2, Object id: 3 parent_id: 2 ]