Skip to content

Instantly share code, notes, and snippets.

@sebjwallace
Last active April 9, 2016 15:52
Show Gist options
  • Save sebjwallace/971b45c490547e39f6b10babc5e455d0 to your computer and use it in GitHub Desktop.
Save sebjwallace/971b45c490547e39f6b10babc5e455d0 to your computer and use it in GitHub Desktop.
Convert an array-tree into an vTree

Writing hyperscript can get tedious when repeating this syntax for every element.

h('div', 'this is an element', [
  h('ul', [
    h('li', 'writing all these h calls')
    h('li', 'can get boring...')
  ])  
])

Instead it would be nicer to express the same thing but as arrays:

['div', 'this is an element',
  ['ul',
    ['li', 'much better'],
    ['li', 'about as clean as it can get...']
  ]
]

This gist offers a single algorithm to convert an array tree into a vTree to make the development experience a bit nicer.

Here is a sample jsbin

function template(t){
var tag = t[0], attributes, children;
if(typeof t[1] == 'object' && !Array.isArray(t[1]))
attributes = t[1];
children = t.map(function(e,i){
if(Array.isArray(e))
return template(e);
else if(typeof e == 'string' && i > 0)
return e;
});
return h(tag,attributes,children);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment