views:

198

answers:

1

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?

+10  A: 

The exec method will receive a string, because the Boolean Logical Operators can return an operand, and not necessarily a Boolean result, for example:

The Logical AND operator (&&), will return the value of the second operand if the first is truthy:

true && "foo"; // "foo"

And it will return the value of the first operand if it is by itself falsy:

NaN && "anything"; // NaN
0 && "anything";   // 0

The Logical OR operator (||) will return the value of the second operand, if the first one is falsy:

false || "bar"; // "bar"

And it will return the value of the first operand if it is by itself non-falsy:

"foo" || "anything"; // "foo"

Falsy values are: null, undefined, NaN, 0, zero-length string, and of course false.

Anything else, evaluated in boolean context is truthy (will coerce to true).

So, let's look the expression:

var test = /(-?)(\d*)n((?:\+|-)?\d*)/.exec(
  match[2] === "even" && "2n" ||  // return '2n' if match[2] is 'even'
  match[2] === "odd" && "2n+1" || // return '2n+1' if it's 'odd'
  !/\D/.test(match[2]) && "0n+" + match[2]|| // return '0n+N' if it's a digit(N) 
  match[2]  // otherwise, return the match[2] value
 );
CMS
Thanks! Very clear explanation!
Andy Li
bobince
@bobnice: I agree with you, I don't quite like how they use the logical operators in this snippet, but I'm not sure *why* they did it in this way, since the ternary operator would actually *save 6 characters*... any thoughts ?
CMS