Skip to content

Instantly share code, notes, and snippets.

@vdeturckheim
Last active October 28, 2015 20:31
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save vdeturckheim/0de64e58bc2cbc733448 to your computer and use it in GitHub Desktop.
Save vdeturckheim/0de64e58bc2cbc733448 to your computer and use it in GitHub Desktop.
Proper (according to me) "contains" method for arrays in javascript. This allows the use of callback on testing.
/**
* Proper (according to me) "isPresent" method for arrays in javascript. This allows the use of callback on testing.
* An empty callback is like using '==' as test.
* @param item item to find
* @param cpf -optional- test callback function: function(a,b) where a is the element to find and b the element tested
* from the array.
* @returns {boolean} true if at least one element is present in the array equals to the one to find according to the
* compare function.
* @author Vladimir de Turckheim
*/
Array.prototype.isPresent = function ( item , cpf ) {
if ( ! cpf ) {
cpf = function ( a , b ) {
return a === b;
}
}
return ! this.every ( function ( elt ) {
return ! cpf ( item , elt );
} );
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment