Skip to content

Instantly share code, notes, and snippets.

@stevekinney
Created September 2, 2018 18:07
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save stevekinney/b5779ba19d9a0a98d7f368690312184b to your computer and use it in GitHub Desktop.
Save stevekinney/b5779ba19d9a0a98d7f368690312184b to your computer and use it in GitHub Desktop.
/**
* Creates as an iterable queue for use in a breadth-first search.
*
* If you iterate over this queue, you will get a breadth-first search for
* free.
*
* @param rootNode - First node to add to the queue.
* @yields The next AST node in the queue.
* @returns The complete queue of nodes that were added.
*
*/
export function* createNodeQueue(root: ASTNode): IterableIterator<ASTNode> {
const queue: ASTNode[] = [root];
for (const node of queue) {
queue.push(...getChildNodes(node));
yield node;
}
return queue;
}
/**
* Gets all of the child nodes if there are any.
*
* Gracefully falls back to an empty array if you provide a node that doesn't
* support child nodes (e.g. a text node or comment node).
*
* @param node An AST Node
* @returns An array of AST Nodes that are the children of the provided node.
*/
export const getChildNodes = (node: ASTNode): ASTNode[] => node.childNodes || [];
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment