Created
June 20, 2012 20:19
-
-
Save nekman/2961970 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/*! | |
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