Skip to content

Commit b030861

Browse files
jviidemichaelficarra
authored andcommitted
Avoid .indexOf in nthChild
1 parent b77abf7 commit b030861

File tree

1 file changed

+12
-15
lines changed

1 file changed

+12
-15
lines changed

esquery.js

Lines changed: 12 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -216,18 +216,18 @@ function createMatcher(selector) {
216216
};
217217

218218
case 'nth-child': {
219-
const idxFn = () => selector.index.value - 1;
219+
const nth = selector.index.value;
220220
return (node, ancestry, options) => {
221221
return matches(node, selector.right, ancestry, options) &&
222-
nthChild(node, ancestry, idxFn, options);
222+
nthChild(node, ancestry, nth, false, options);
223223
};
224224
}
225225

226226
case 'nth-last-child': {
227-
const idxFn = (length) => length - selector.index.value;
227+
const nth = selector.index.value;
228228
return (node, ancestry, options) => {
229229
return matches(node, selector.right, ancestry, options) &&
230-
nthChild(node, ancestry, idxFn, options);
230+
nthChild(node, ancestry, nth, true, options);
231231
};
232232
}
233233

@@ -397,30 +397,27 @@ function adjacent(node, selector, ancestry, side, options) {
397397
return false;
398398
}
399399

400-
/**
401-
* @callback IndexFunction
402-
* @param {Integer} len Containing list's length
403-
* @returns {Integer}
404-
*/
405-
406400
/**
407401
* Determines if the given node is the nth child, determined by
408402
* `idxFn`, which is given the containing list's length.
409403
* @param {external:AST} node
410404
* @param {external:AST[]} ancestry
411-
* @param {IndexFunction} idxFn
405+
* @param {Integer} nth
406+
* @param {boolean} fromEnd
412407
* @param {ESQueryOptions|undefined} options
413408
* @returns {boolean}
414409
*/
415-
function nthChild(node, ancestry, idxFn, options) {
410+
function nthChild(node, ancestry, nth, fromEnd, options) {
411+
if (nth <= 0) { return false; }
416412
const [parent] = ancestry;
417413
if (!parent) { return false; }
418414
const keys = getVisitorKeys(parent, options);
419415
for (let i = 0; i < keys.length; i++) {
420416
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+
}
424421
}
425422
}
426423
return false;

0 commit comments

Comments
 (0)