All files / src/matchers adjacent.ts

90.48% Statements 19/21
69.57% Branches 16/23
100% Functions 3/3
90.48% Lines 19/21

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 32 33 34 35 36 37 38 39 40 41 42  17x 17x       17x 17x   17x 28x               2x 2x     2x 2x 7x 7x 6x 6x 4x     2x 1x   1x       2x      
// Dependencies:
import { findMatches } from '../match';
import { getVisitorKeys } from '../traverse';
import { TSQueryNode, TSQuerySelectorNode } from '../tsquery-types';
 
// Constants:
const LEFT = 'left';
const RIGHT = 'right';
 
export function adjacent (node: TSQueryNode, selector: TSQuerySelectorNode, ancestry: Array<TSQueryNode>): boolean {
    return findMatches(node, selector.right, ancestry) &&
        findAdjacent(node, selector.left, ancestry, LEFT) ||
        selector.right.subject &&
        findMatches(node, selector.left, ancestry) &&
        findAdjacent(node, selector.right, ancestry, RIGHT);
}
 
function findAdjacent (node: TSQueryNode, selector: TSQuerySelectorNode, ancestry: Array<TSQueryNode>, side: string): boolean {
    const [parent] = ancestry;
    Iif (!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);
            if (index === -1) {
                return false;
            }
 
            if (side === LEFT && index > 0 && findMatches(prop[index - 1], selector, ancestry)) {
                return true;
            }
            Iif (side === RIGHT && index < prop.length - 1 && findMatches(prop[index + 1], selector, ancestry)) {
                return true;
            }
        }
        return false;
    });
}