or

Returns an element from an array when it matches a condition

Returns the element of an array when the callback returns true.

This module provides a similar function as Array.prototype.filter, but it returns the element, not an array. And it stops looping as soon as it finds a result.

var arr = ['item', 'other', 'finally'];
 
var item = or(arr, function(item) {
    return item === 'other';
});
 
console.log(item); // "other" 
 
// Real world example 
var matchesSelector = function() {
    var shims = ['matchesSelector', 'mozMatchesSelector',
        'webkitMatchesSelector', 'oMatchesSelector', 'msMatchesSelector'];
 
    return or(shims, function(shim) {
        return shim in document;
    });
}();
 
document.getElementById('some')[matchesSelector]('#some'); // true 

The module returns a function accepting the following arguments:

  • array: the array on which to iterate
  • callback: the function being called
  • context: the context on which to call the callback

MIT License.