Having this as input '<apple, <pear>>, <orange, <apple>, <cherry>, banana>, <banana, <pear>, <orange>>'
having in mind that whatever is inside angle brackets is considered a node, so the output should be:
['<apple, <pear>>', '<orange, <apple>, <cherry>, banana>', '<banana, <pear>, <orange>>']
I’ve tried regex and split like this
const regexBycomma = /([^,<]*(?:<[^>]*>[^,<]*)*),?/g;
str.split(regexBycomma);
with not good results, also many algorithms like this one:
function getParentNodes(input) {
const nodes = input.match(/<[^<>]+>/g); // Extract all nodes from the input
const parentNodes = [];
let currentParentNode = '';
for (const node of nodes) {
if (currentParentNode === '') {
currentParentNode = node;
} else if (node.startsWith(currentParentNode)) {
currentParentNode += ',' + node;
} else {
parentNodes.push(currentParentNode);
currentParentNode = node;
}
}
if (currentParentNode !== '') {
parentNodes.push(currentParentNode);
}
return parentNodes;
}
2
Answers
Here the idea is to track how deep you are in to the nodes by adding to the depth when encountering a
<
and reducing it when encounting a>
. When the depth becomes zero start a new string.You might just naively count opened and closed brackets and push "nodes" to the result: