All files / src match.ts

87.5% Statements 21/24
71.43% Branches 10/14
100% Functions 4/4
86.96% Lines 20/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    17x 17x     17x 53x 53x 53x       53x   1495x 1443x   1495x 307x       1495x     53x     2806x 2806x 172x   2634x       2634x 2634x 2634x          
// Dependencies:
import { Node } from 'typescript';
import { MATCHERS } from './matchers';
import { traverse } from './traverse';
import { TSQueryNode, TSQuerySelectorNode } from './tsquery-types';
 
export function match<T extends Node = Node> (node: Node | TSQueryNode<T>, selector: TSQuerySelectorNode): Array<TSQueryNode<T>> {
    const ancestry: Array<TSQueryNode<T>> = [];
    const results: Array<TSQueryNode<T>> = [];
    Iif (!selector) {
        return results;
    }
 
    traverse(node, {
        enter (child: TSQueryNode<T>, parent: TSQueryNode<T> | null): void {
            if (parent != null) {
                ancestry.unshift(parent);
            }
            if (findMatches(child, selector, ancestry)) {
                results.push(child);
            }
        },
        leave (): void {
            ancestry.shift();
        }
    });
    return results;
}
 
export function findMatches<T extends Node = Node> (node: TSQueryNode<T>, selector: TSQuerySelectorNode, Iancestry: Array<TSQueryNode<T>> = []): boolean {
    if (!selector) {
        return true;
    }
    Iif (!node) {
        return false;
    }
 
    const matcher = MATCHERS[selector.type];
    Eif (matcher) {
        return matcher(node, selector, ancestry);
    }
 
    throw new Error(`Unknown selector type: ${selector.type}`);
}