JSFiddle - React, Tailwind, and code Playground
by Luiz Silva
HTML
<pre id="result"></pre>
JavaScript
var astTree = {
type: "IfClause",
base:
{
type: "Boolean",
value: false
},
body: [
{ type: "Var" },
{
type: "ForClause",
body: [
{ type: "VarIncrement" }
]
},
{ type: "Return" },
]
};
var flatten = function(node) {
var list = [];
function consume(node) {
list.push(node);
if ('body' in node) {
var endNode = { type: node.type + 'End' }
node.type += "Start";
node.body.forEach(consume);
list.push(endNode);
delete node.body;
}
}
consume(node);
return list;
}
document.querySelector('#result').innerText = JSON.stringify(flatten(astTree), null, ' ');