Created
November 12, 2017 00:47
-
-
Save pluma/1c4a6e4d7e734c198befdbb9b44c5b36 to your computer and use it in GitHub Desktop.
Creating a DOM-like element tree from JSONML
This file contains hidden or 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
function isObject(obj) { | |
if (!obj) return false; | |
if (typeof obj !== "object") return false; | |
if (Array.isArray(obj)) return false; | |
return true; | |
} | |
class Element { | |
constructor(tagName, attributes, ...children) { | |
this.tagName = tagName; | |
this.attributes = { ...attributes }; | |
this.children = children; | |
} | |
get innerText() { | |
return this.children.reduce( | |
(textContent, child) => | |
textContent + | |
(child instanceof Element ? child.innerText : String(child)), | |
"" | |
); | |
} | |
find(tagName, ...tagNames) { | |
if (tagName === "#") return this.innerText; | |
const child = this.children.find( | |
child => child instanceof Element && child.tagName === tagName | |
); | |
if (!child) return undefined; | |
if (!tagNames.length) return child; | |
return child.find(...tagNames); | |
} | |
} | |
function createElement(tagName, ...children) { | |
const attributes = {}; | |
if (isObject(children[0])) { | |
Object.assign(attributes, children.shift()); | |
} | |
return new Element( | |
tagName, | |
attributes, | |
...children.map(child => { | |
if (!Array.isArray(child)) return String(child); | |
return createElement(...child); | |
}) | |
); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment