Explain a block of crazy JS code inside Sizzle(the CSS selector engine)

Posted by Andy Li on Stack Overflow See other posts from Stack Overflow or by Andy Li
Published on 2010-03-27T08:12:31Z Indexed on 2010/03/27 8:13 UTC
Read the original article Hit count: 274

Filed under:
|
|

So, here is the function for pre-filtering "CHILD":

function(match){
    if ( match[1] === "nth" ) {
        // parse equations like 'even', 'odd', '5', '2n', '3n+2', '4n-1', '-n+6'
        var test = /(-?)(\d*)n((?:\+|-)?\d*)/.exec(
            match[2] === "even" && "2n" || match[2] === "odd" && "2n+1" ||
            !/\D/.test( match[2] ) && "0n+" + match[2] || match[2]);

        // calculate the numbers (first)n+(last) including if they are negative
        match[2] = (test[1] + (test[2] || 1)) - 0;
        match[3] = test[3] - 0;
    }

    // TODO: Move to normal caching system
    match[0] = done++;

    return match;
}

The code is extracted from line 442-458 of sizzle.js.

So, why is the line var test = ..., have the exec inputing a boolean? Or is that really a string?

Can someone explain it by splitting it into a few more lines of code?

© Stack Overflow or respective owner

Related posts about JavaScript

Related posts about sizzle