All files / src/matchers nth-child.ts

100% Statements 18/18
91.67% Branches 11/12
100% Functions 6/6
100% Lines 18/18

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31  17x 17x     17x 86x 12x     17x 86x 12x       172x 172x 4x   168x 168x 480x 480x 88x 88x   392x      
// Dependencies:
import { findMatches } from '../match';
import { getVisitorKeys } from '../traverse';
import { TSQueryNode, TSQuerySelectorNode } from '../tsquery-types';
 
export function nthChild (node: TSQueryNode, selector: TSQuerySelectorNode, ancestry: Array<TSQueryNode>): boolean {
    return findMatches(node, selector.right, ancestry) &&
        findNthChild(node, ancestry, () => (selector.index.value as number) - 1);
}
 
export function nthLastChild (node: TSQueryNode, selector: TSQuerySelectorNode, ancestry: Array<TSQueryNode>): boolean {
    return findMatches(node, selector.right, ancestry) &&
        findNthChild(node, ancestry, (length: number) => length - (selector.index.value as number));
}
 
function findNthChild (node: TSQueryNode, ancestry: Array<TSQueryNode>, getIndex: (length: number) => number): boolean {
    const [parent] = ancestry;
    if (!parent) {
        return false;
    }
    const keys = getVisitorKeys(node.parent as TSQueryNode || null);
    return keys.some(key => {
        const prop = (node.parent as any)[key];
        if (Array.isArray(prop)) {
            const index = prop.indexOf(node);
            return index >= 0 && index === getIndex(prop.length);
        }
        return false;
    });
}