Skip to content

Instantly share code, notes, and snippets.

@petamoriken
Last active October 23, 2019 03:25
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save petamoriken/99e2167f57365d437e5b24f24da6feab to your computer and use it in GitHub Desktop.
Save petamoriken/99e2167f57365d437e5b24f24da6feab to your computer and use it in GitHub Desktop.
/**
* Node を順に列挙する
*
* @param {Node} root
* @param {?{ whatToShow?: number, filter?: NodeFilter, direction?: "capture" | "bubbling" }} options
* @param {"capture" | "bubbling"} options.direction - "capture" では現れる順に列挙し、 "bubbling" では子を持つ Node は子から列挙する
* @return {Generator<Node>}
*/
function* createNodeIterator(root, options = {}) {
const { whatToShow, filter } = options;
const direction = options.direction === "bubbling" ? "bubbling" : "capture";
if (direction === "capture") {
const iterator = document.createNodeIterator(root, whatToShow, filter);
for (;;) {
const current = iterator.nextNode();
if (current !== null) {
yield current;
} else {
return;
}
}
} else {
const walker = document.createTreeWalker(root, whatToShow, filter);
for (;;) {
while (walker.firstChild() !== null) {}
yield walker.currentNode;
while (walker.nextSibling() === null) {
const current = walker.parentNode();
if (current !== null) {
yield current;
} else {
return;
}
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment