I have an algorythmic problem with generating dynamically nested lists. On input i get an array of strings like that:
['A', 'A', '/B', '//C', '/B', '//C', 'A', 'A']
Each '/' is next level in hierarchy, and it is direct child of the last element with lesser amount of '/' signs. Elements with the same amount of '/' signs are on the same level.
Inputs like ['A', '//C'] or ['//C'] are invalid.
Result for that should be HTML lists in hierarchy A A -B --C -B --C A A
This is so far what i did: https://jsfiddle.net/k18Lbou7/
function createList(depth, elements, iterator, parentElement) {
var newDepth = 0;
for(var i=iterator; i<elements.length; i++) {
var match = elements[i].text.match(/^\s*(\/+)/);
if(match == null) {
newDepth = 0;
} else {
newDepth = match[0].length;
}
if (depth == newDepth-1) {
var nestedList = document.createElement('ul');
parentElement.lastChild.appendChild(nestedList);
createList(newDepth, elements, i, nestedList);
} else if (depth == newDepth) {
var nextElement = document.createElement('li');
var span = document.createElement('span');
span.innerHTML = elements[i].text;
nextElement.appendChild(span);
parentElement.appendChild(nextElement);
}
}
}
var value = ['Home', '* This is active', '/This is dropdown', '// shhh...', '/ we ♥ you', '//Last one', 'Last one', 'Last one']
.map(function(pLine) {
return {
'text': pLine,
'page_id': null
};
});
var listElement = document.createElement('ul');
createList(0, value, 0, listElement);
document.body.appendChild(listElement);
The key is that I'm duplicating some keys, or avoiding the last elements in different approaches.
Maybe someone can help mi with spotting the reason of bad result or suggest different method for resolving this feature.
Big Thanks for help!