Skip to content

Instantly share code, notes, and snippets.

@pluma
Created November 12, 2017 00:47
Show Gist options
  • Select an option

  • Save pluma/1c4a6e4d7e734c198befdbb9b44c5b36 to your computer and use it in GitHub Desktop.

Select an option

Save pluma/1c4a6e4d7e734c198befdbb9b44c5b36 to your computer and use it in GitHub Desktop.

Revisions

  1. pluma created this gist Nov 12, 2017.
    46 changes: 46 additions & 0 deletions jsonmlElement.js
    Original 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);
    })
    );
    }