Created
November 12, 2017 00:47
-
-
Save pluma/1c4a6e4d7e734c198befdbb9b44c5b36 to your computer and use it in GitHub Desktop.
Revisions
-
pluma created this gist
Nov 12, 2017 .There are no files selected for viewing
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 charactersOriginal file line number Diff line number Diff line change @@ -0,0 +1,46 @@ 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); }) ); }