Skip to content

Instantly share code, notes, and snippets.

@padolsey
Created October 16, 2012 18:56
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 4 You must be signed in to fork a gist
  • Save padolsey/3901222 to your computer and use it in GitHub Desktop.
Save padolsey/3901222 to your computer and use it in GitHub Desktop.
// 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}
@padolsey
Copy link
Author

The spec could be improved to make the implementation smaller. E.g. An array could be passed to domBuilder instead of relying on arguments. And we could use innerHTML instead of creating a text-node, but that'd probably break things unexpectedly.

Can anyone make it smaller than 254 bytes?

@padolsey
Copy link
Author

(Can anyone make it smaller without sacrificing the specified functionality?)

@jcutrell
Copy link

Not sure if using this would help save space / even work, but: !b.sort && d.appendChild(m.createTextNode(b)) || for (c in

@tobitailor
Copy link

Got it down to 232 bytes.

@tobitailor
Copy link

Could save another 7 bytes by using simple strings instead of regexp literals to specify tag names.

@padolsey
Copy link
Author

@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