Created
July 21, 2016 21:46
-
-
Save rvighne/8b08ce42a9f1a51675a4972b843ef0a5 to your computer and use it in GitHub Desktop.
Wraps the TreeWalker interface into a generator function, for simpler and more idiomatic usage.
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
/* | |
SYNTAX: | |
Generator treeIterator(Node root, int whatToShow, bool function filter(Node)) | |
- root: The parent node. It is not returned. | |
- whatToShow: Bitmask of the NodeFilter.SHOW_* static constants. Represents the types of nodes included. | |
- filter: Predicate returning whether the node given as the first argument should be included in the iteration. | |
Instead of a boolean, it may return a NodeFilter.FILTER_* static constant. | |
A return value of `true` is implicitly converted to `NodeFilter.FILTER_ACCEPT`, | |
and `false` becomes `NodeFilter.FILTER_REJECT` | |
EXAMPLE: Print the text of every non-whitespace text node in the page | |
for (let node of treeIterator(document.body, NodeFilter.SHOW_TEXT, node => /\S/.test(node.nodeValue))) | |
console.log(node.nodeValue); | |
*/ | |
function* treeIterator(root, whatToShow, filter) { | |
let treeWalker; | |
if (typeof filter === 'function') { | |
treeWalker = document.createTreeWalker(root, whatToShow, { | |
acceptNode: node => { | |
let ret = filter(node); | |
if (ret === true) | |
return NodeFilter.FILTER_ACCEPT; | |
else if (ret === false) | |
return NodeFilter.FILTER_REJECT; | |
else | |
return ret; | |
} | |
}); | |
} else { | |
treeWalker = document.createTreeWalker(root, whatToShow); | |
} | |
while (treeWalker.nextNode()) | |
yield treeWalker.currentNode; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment