Skip to content

Instantly share code, notes, and snippets.

@codenothing
Created May 1, 2010 07:14
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 codenothing/386118 to your computer and use it in GitHub Desktop.
Save codenothing/386118 to your computer and use it in GitHub Desktop.
/*
* Duck Punched Filter
* May 1, 2010
* Corey Hart @ http://www.codenothing.com
*/
(function( $, undefined ) {
// Keep a copy of the old filter for reference
var old = $.fn.filter;
// Create space for holding filter custom filter functions
$.filters = {};
// Overload the filter method
$.fn.filter = function( pass, args, fn ) {
// Make sure the qualifier was passed, otherwise use old filter
if ( args === undefined ) {
return old.apply( this, arguments );
}
// Reorganize
if ( $.isArray( pass ) ) {
fn = args;
args = pass;
pass = false;
}
else if ( $.isFunction( args ) ) {
fn = args;
if ( typeof pass == 'boolean' ) {
args = [];
} else {
args = pass;
pass = false;
}
}
// Setup qualifier to allow a stored reference or anonymous function
fn = typeof fn == 'string' ? $.filters[ fn ] : fn;
var self = this, elems = [], i = -1, l = self.length;
// Allow for full control of elems stack creation
if ( pass === true ) {
// Convert the current stack into array of elements, and spot
// it at the first position
args.unshift( self.toArray() );
elems = fn.apply( self, args ) || [];
}
else {
// Configure new set of elements based on qualifier and the 2 first
// spots in the arguments for index and current element
args.unshift( null );
args.unshift( null );
for ( ; ++i < l; ) {
args[ 0 ] = i;
args[ 1 ] = self[ i ];
if ( fn.apply( self[ i ], args ) === true ) {
elems.push( self[ i ] );
}
}
}
// Make the new jquery object
return self.pushStack( elems, 'filter', fn );
};
})( jQuery );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment