Created
August 21, 2017 02:30
-
-
Save mateusvahl/12c7579ed40abe5d2ff0b821b5b2cc01 to your computer and use it in GitHub Desktop.
Javascript html structure like hiccup
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
// http://ramdajs.com/repl/#?const%20parseAttributes%20%3D%20pipe%28%0A%20%20toPairs%2C%0A%20%20map%28%28%5Bkey%2C%20val%5D%29%20%3D%3E%20val%20%3F%20%60%24%7Bkey%7D%3D%22%24%7Bval%7D%22%60%20%3A%20key%29%2C%0A%20%20join%28%27%20%27%29%0A%29%3B%0A%0Aconst%20render%20%3D%20%28%5Btag%2C%20...rest%5D%29%20%3D%3E%20%7B%0A%20%20if%28%21tag%29%20return%3B%0A%20%20%0A%20%20var%20attributes%20%3D%20rest%5B0%5D%3B%0A%20%20var%20body%20%3D%20rest.slice%281%29%3B%0A%20%20%0A%20%20if%28Array.isArray%28attributes%29%20%7C%7C%20is%28String%2C%20attributes%29%29%20%7B%0A%20%20%20%20body%20%3D%20%5Battributes%2C%20...rest.slice%281%29%5D%3B%0A%20%20%20%20attributes%20%3D%20%7B%7D%3B%0A%20%20%20%7D%0A%20%20%20%0A%20const%20attributesRendered%20%3D%20parseAttributes%28attributes%29%3B%0A%20const%20a%20%3D%20attributesRendered%20%3F%20%27%20%27%20%2B%20attributesRendered%20%3A%20%27%27%3B%0A%20const%20b%20%3D%20body.map%28_%20%3D%3E%20is%28String%2C%20_%29%20%3F%20_%20%3A%20render%28_%29%29.join%28%27%27%29%3B%0A%20%20%0A%20return%20%60%3C%24%7Btag%7D%24%7Ba%7D%3E%24%7Bb%7D%3C%2F%24%7Btag%7D%3E%60%0A%7D%0A%0Arender%28%5B%22html%22%2C%0A%20%20%20%20%20%20%20%20%5B%22head%22%2C%20%7Bx%3A1%7D%5D%2C%0A%20%20%20%20%20%20%20%20%5B%22body%22%5D%0A%20%5D%29%3B | |
const parseAttributes = pipe( | |
toPairs, | |
map(([key, val]) => val ? `${key}="${val}"` : key), | |
join(' ') | |
); | |
const render = ([tag, ...rest]) => { | |
if(!tag) return; | |
var attributes = rest[0]; | |
var body = rest.slice(1); | |
if(Array.isArray(attributes) || is(String, attributes)) { | |
body = [attributes, ...rest.slice(1)]; | |
attributes = {}; | |
} | |
const attributesRendered = parseAttributes(attributes); | |
const a = attributesRendered ? ' ' + attributesRendered : ''; | |
const b = body.map(_ => is(String, _) ? _ : render(_)).join(''); | |
return `<${tag}${a}>${b}</${tag}>` | |
} | |
render(["html", | |
["head", {x:1}], | |
["body"] | |
]); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment