Skip to content

Instantly share code, notes, and snippets.

@tsiq-swyx
Created February 1, 2018 14:37
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tsiq-swyx/6e406366deb7d2023ed710a77f9239d5 to your computer and use it in GitHub Desktop.
Save tsiq-swyx/6e406366deb7d2023ed710a77f9239d5 to your computer and use it in GitHub Desktop.
FreeGratefulOstracod created by anonymous - https://repl.it/repls/FreeGratefulOstracod
function astParse(a) {
const arr = a.split(',')
let ast = []
let currentLevel = 0
let currentNode = null
arr.forEach(tag => {
const taglevel = tag.search(/[^_]/) // gives how many underscores
const tagNode = {
name: tag.slice(taglevel),
children: []
}
if (taglevel > currentLevel) {
currentNode.children.push(tagNode)
} else {
ast.push(tagNode)
}
currentNode = tagNode
})
return ast
}
function astPrint(a) {
let ans = ''
a.forEach(x => {
ans += `<${x.name}>`
if (x.children.length) ans += astPrint(x.children)
ans += `</${x.name}>`
})
return ans
}
function parse(a) {
return astPrint(astParse(a))
}
console.log('test2')
testStr = 'div,span,h1,_span,__a'
console.log('should return')
console.log('<div></div><span></span><h1><span><a></a></span></h1>')
console.log(parse(testStr))
console.log('-------')
console.log('test3')
testStr = "div,_p,__h1,'foo',_p,'bar'"
console.log('should return')
console.log('<div><p><h1>foo</h1></p><p>bar</p></div>')
console.log(parse(testStr))
console.log('-------')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment