Created
February 1, 2018 14:37
-
-
Save tsiq-swyx/6e406366deb7d2023ed710a77f9239d5 to your computer and use it in GitHub Desktop.
FreeGratefulOstracod created by anonymous - https://repl.it/repls/FreeGratefulOstracod
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
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