Created
September 2, 2018 18:07
-
-
Save stevekinney/b5779ba19d9a0a98d7f368690312184b to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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