Skip to content

Instantly share code, notes, and snippets.

@nekman
Created June 20, 2012 20:19
Show Gist options
  • Save nekman/2961970 to your computer and use it in GitHub Desktop.
Save nekman/2961970 to your computer and use it in GitHub Desktop.
/*!
Written for education purpose.
Could use Array.filter / Array.map instead.
Example:
//Returns an array with one object: {name:'foo'}
var result = { packages : [{name:'foo'}, {name:'bar'}, {name:'baz'}] };
result.packages.where(function() {
var name = this.name;
return name && name.match(/fo/g);
});
//Returns an array of even numbers: [2,4,6]
[1,2,3,4,5,6].where(function() {
return this % 2 === 0;
});
*/
(function() {
'use strict';
Array.prototype.where = Array.prototype.where || function(predicate) {
var results = [];
if (typeof predicate !== 'function') {
return results;
}
var len = this.length,
i = 0;
while (i < len) {
var item = this[i++];
if (predicate.call(item)) {
results.push(item);
}
}
return results;
};
}());
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment