JSFiddle - React, Tailwind, and code Playground
by shubham sharma
JavaScript
var myParser = function(lines, marker) {
var populatefn = populatefn || function(obj) { return obj;};
var marker = marker || '\t';
function addHiddenProperties(scope, props) {
for (p in props) {
Object.defineProperty(scope, p, {enumerable: false, value: props[p]});
}
}
var TreeNode = function(data, depth) {
this.parent = null;
addHiddenProperties(this, {
'data':data,
'depth':depth,
'parent':null,
'children':[]
});
this[data||'root']=this.children;
}
TreeNode.prototype.toString = function() {
return JSON.stringify(this.children);
}
var tree = new TreeNode(null, -1);
var levels = [tree];
function countTabs(line) {
var count = 0;
for (var i = 0; i < line.length; i++) {
var ch = line[i];
if ((ch == '\t')) {
count += 1;
}else if (/[^\s]/.test(ch)){
return count;
}
}
return -1; // no content
}
for (var i = 0; i < lines.length; i++) {
var line = lines[i];
var tabcount = countTabs(line);
if (tabcount >= 0) { //then add node to tree
function topnode() {
return levels[levels.length - 1];
}
while(tabcount - topnode().depth <= 0) {
levels.pop();
}
var depth = levels.length - 1;
var node = new TreeNode(line.substring(tabcount), depth);
node.parent = topnode();
node.parent.children.push(node);
levels.push(node);
}
}
return tree;
};
var textAreaOutput = "342\n\tAlvin\n\t\tRoad\nDucksburg\n\tcxzxcz\n\t\taddwqeqe\n\tzcxxzc\n\twqqwe\nqweqwe\n\tmnbmbnmb";
var tree = myParser(textAreaOutput.split("\n"), '\t');
console.log(JSON.stringify(tree.root, null, 4));