Skip to content

Argument to only return first match #71

Open
rvagg opened this Issue Feb 9, 2012 · 0 comments

1 participant

@rvagg
Collaborator
rvagg commented Feb 9, 2012

@benvinegar's query on Twitter about being able to return the first match only got me thinking that it may not be that difficult to implement and would actually be quite helpful in many situations.

So here's a first go at hacking a solution, no tests and begging for review by other eyes: rvagg/qwery@master...first

The basic idea is to use querySelector() where available, then we fall back to _qwery() for odd queries or where querySelector() isn't available. We then shortcut the various paths to matches when we have asked for a first and have found a result. There's a few places this needs to be done and my implementation isn't quite optimal because there's currently no way to halt an each() call so we end up doing a bunch of useless loops, but that could be easily fixed by special handling of return false.

Of course, there's still the document-order problem (see #63), so any documentation around use of this functionality would need to stress that you may not get the same result for queries with groups in old vs new browsers because of the differences between querySelector() and what selectNonNative does with splitting the query... Or, someone could fix #63.

Also put in a simple $.first('selector') to the Ender bridge.

In its current form it adds 109 bytes to minified gzipped Qwery.

And, FWIW, NWMatcher has a neat callback feature where you pass in a function that gets called on each match so you can process elements one by one but if you return a false then it'll halt processing so you can use it to implement a first() which halts on first match, see the NW Ender bridge.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Something went wrong with that request. Please try again.