Created
October 16, 2012 18:56
-
-
Save padolsey/3901222 to your computer and use it in GitHub Desktop.
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
// From the 140bytes wishlist here: https://github.com/jed/140bytes/wiki/Wishlist | |
// TASK: | |
// Create a function which can create a DOM structure from this: | |
// | |
domBuilder( | |
[/HTML/], | |
[/HEAD/], | |
[/TITLE/], | |
"Wouldn't this be cool?", | |
[], | |
[], | |
[/BODY/], | |
[/DIV/, {id: "container"}], | |
"Hello, world", | |
[], | |
[], | |
[] | |
); | |
// => | |
// <html> | |
// <head><title>Wouldn't this be cool?</title></head> | |
// <body><div id="container">Hello, world</div></body> | |
// </html> | |
///////////////////// | |
// My implementation: | |
///////////////////// | |
function domBuilder(a, b, c, d, i, m) { | |
a = [].slice.call(arguments); | |
for (d = i = 0,m=document; b = a[i++];) | |
if (b.sort) // an array? | |
for ( | |
c in | |
// NOTE: this is not a notable part of the for..in -- it is placed here for space-saving | |
// Here we create a new child or traverse upwards if b[0] isn't defined: | |
d = b[0] ? (c = m.createElement(b[0].source),d ? d.appendChild(c) : c) : d.parentNode || d, | |
b[1] | |
) // apply attribute: | |
d[c]=b[1][c]; | |
else // a string? -- add text: | |
d.appendChild(m.createTextNode(b)); | |
return d; | |
} | |
/////////////////////// | |
// Minified (254 bytes) | |
/////////////////////// | |
function domBuilder(e,b,c,a,f,d){e=[].slice.call(arguments);a=f=0;for(d=document;b=e[f++];)if(b.sort)for(c in a=b[0]?(c=d.createElement(b[0].source),a?a.appendChild(c):c):a.parentNode||a,b[1])a[c]=b[1][c];else a.appendChild(d.createTextNode(b));return a} |
Could save another 7 bytes by using simple strings instead of regexp literals to specify tag names.
@jcutrell, unfortunately statements can't go in expressions, i.e the for (i in...)
loop
@tobeytailor, ahh nice work! I was so set in my ways with [].slice.call(args)
that I forgot that it is just an array-like thing.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Got it down to 232 bytes.