All files / src/matchers sibling.ts

82.61% Statements 19/23
58.82% Branches 10/17
80% Functions 4/5
82.61% Lines 19/23

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 43 44 45 46  17x 17x       17x 17x   17x 28x               1x 1x     1x 1x 6x 6x 5x 5x 4x     1x 1x 1x                 1x      
// Dependencies:
import { findMatches } from '../match';
import { getVisitorKeys } from '../traverse';
import { TSQueryNode, TSQuerySelectorNode } from '../tsquery-types';
 
// Constants:
const LEFT = 'left';
const RIGHT = 'right';
 
export function sibling (node: TSQueryNode, selector: TSQuerySelectorNode, ancestry: Array<TSQueryNode>): boolean {
    return findMatches(node, selector.right, ancestry) &&
        findSibling(node, selector.left, ancestry, LEFT) ||
        selector.left.subject &&
        findMatches(node, selector.left, ancestry) &&
        findSibling(node, selector.right, ancestry, RIGHT);
}
 
function findSibling (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;
            }
 
            Eif (side === LEFT) {
                return prop.slice(0, index).some(precedingSibling => {
                    return findMatches(precedingSibling, selector, ancestry);
                });
            }
            if (side === RIGHT) {
                return prop.slice(index, prop.length).some(followingSibling => {
                    return findMatches(followingSibling, selector, ancestry);
                });
            }
        }
        return false;
    });
}