Last active
October 23, 2019 03:25
-
-
Save petamoriken/99e2167f57365d437e5b24f24da6feab 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
/** | |
* 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