@@ -216,18 +216,18 @@ function createMatcher(selector) {
216
216
} ;
217
217
218
218
case 'nth-child' : {
219
- const idxFn = ( ) => selector . index . value - 1 ;
219
+ const nth = selector . index . value ;
220
220
return ( node , ancestry , options ) => {
221
221
return matches ( node , selector . right , ancestry , options ) &&
222
- nthChild ( node , ancestry , idxFn , options ) ;
222
+ nthChild ( node , ancestry , nth , false , options ) ;
223
223
} ;
224
224
}
225
225
226
226
case 'nth-last-child' : {
227
- const idxFn = ( length ) => length - selector . index . value ;
227
+ const nth = selector . index . value ;
228
228
return ( node , ancestry , options ) => {
229
229
return matches ( node , selector . right , ancestry , options ) &&
230
- nthChild ( node , ancestry , idxFn , options ) ;
230
+ nthChild ( node , ancestry , nth , true , options ) ;
231
231
} ;
232
232
}
233
233
@@ -397,30 +397,27 @@ function adjacent(node, selector, ancestry, side, options) {
397
397
return false ;
398
398
}
399
399
400
- /**
401
- * @callback IndexFunction
402
- * @param {Integer } len Containing list's length
403
- * @returns {Integer }
404
- */
405
-
406
400
/**
407
401
* Determines if the given node is the nth child, determined by
408
402
* `idxFn`, which is given the containing list's length.
409
403
* @param {external:AST } node
410
404
* @param {external:AST[] } ancestry
411
- * @param {IndexFunction } idxFn
405
+ * @param {Integer } nth
406
+ * @param {boolean } fromEnd
412
407
* @param {ESQueryOptions|undefined } options
413
408
* @returns {boolean }
414
409
*/
415
- function nthChild ( node , ancestry , idxFn , options ) {
410
+ function nthChild ( node , ancestry , nth , fromEnd , options ) {
411
+ if ( nth <= 0 ) { return false ; }
416
412
const [ parent ] = ancestry ;
417
413
if ( ! parent ) { return false ; }
418
414
const keys = getVisitorKeys ( parent , options ) ;
419
415
for ( let i = 0 ; i < keys . length ; i ++ ) {
420
416
const listProp = parent [ keys [ i ] ] ;
421
- if ( Array . isArray ( listProp ) ) {
422
- const idx = listProp . indexOf ( node ) ;
423
- if ( idx >= 0 && idx === idxFn ( listProp . length ) ) { return true ; }
417
+ if ( Array . isArray ( listProp ) ) {
418
+ if ( nth <= listProp . length && listProp [ fromEnd ? listProp . length - nth : nth - 1 ] === node ) {
419
+ return true ;
420
+ }
424
421
}
425
422
}
426
423
return false ;
0 commit comments