Created
November 21, 2017 01:14
-
-
Save beck/e70c0aaa51b3907e61b5aa8d04abf899 to your computer and use it in GitHub Desktop.
Can you nest generators?
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
// This is an excessively over-engneered solution for when you forget | |
// `node.textContent` strips all child html :) | |
// to run: | |
// node --version # v9.2.0 | |
// npm install jsdom | |
// node recursive-char-generator.js | |
const jsdom = require("jsdom"); | |
const { JSDOM } = jsdom; | |
const dom = new JSDOM(`<!DOCTYPE html> | |
<body>H<div><div><div>e</div></div></div><b>ll</b><p>o</p>!</body>`); | |
function* getElementContentCharGenerator(el) { | |
const children = Array.from(el.childNodes); | |
for(let i = 0; i<children.length; i++) { | |
const child = children[i]; | |
// handle text nodes, yielding each char | |
if(child.constructor.name == 'Text') { | |
let chars = Array.from(child.wholeText); | |
for(let c = 0; c<chars.length; c++) { | |
yield chars[c]; | |
} | |
} | |
// use recursion with non-text nodes | |
const childNodeChars = getElementContentCharGenerator(child); | |
for(let c of childNodeChars) { | |
yield c; | |
} | |
} | |
} | |
const body = dom.window.document.querySelector('body'); | |
for(let c of getElementContentCharGenerator(body)) { | |
console.log(c); | |
// Should output: | |
// H | |
// e | |
// l | |
// l | |
// o | |
// ! | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment