Explain the block of crazy JS code inside Sizzle (CSS picker)

So, here is the "CHILD" prefilter function:

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 the sizzle.js file .

So why the line var test = ...has exec introducing a boolean? Or is it really a string?

Can someone explain this by dividing it into several lines of code?

+3
source share
1 answer

The method execwill receive a string because Boolean operators can return an operand, and not necessarily a Booleanresult, for example:

(&&) , :

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

, :

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

(||) , :

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

, :

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

Falsy: null, undefined, NaN, 0, , , false.

, , ( true).

, :

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 'odd'
  !/\D/.test(match[2]) && "0n+" + match[2]|| // return '0n+N' if it a digit(N) 
  match[2]  // otherwise, return the match[2] value
 );
+10

Source: https://habr.com/ru/post/1738754/


All Articles