3 回答

TA贡献1772条经验 获得超5个赞
最简单的方法是递归地构建一个键映射结构,然后将其转换为树。
keyMapToTree下面的函数使用名为的内部帮助器函数keyMapToTreeInner。
console.log(keyMapToTree(parseAsKeyMap('Foo<Bar, Baz<Qux>>')));
function parseAsKeyMap(input, tree = {}) {
input = input.trim();
let startIndex = input.indexOf('<'),
endIndex = input.lastIndexOf('>');
if (startIndex !== -1 && endIndex === -1) {
throw new Error("Missing closing bracket '>' for " + input);
} else if (startIndex === -1 && endIndex !== -1) {
throw new Error("Missing opening bracket '<' for " + input);
} else if (startIndex !== -1 && endIndex !== -1) {
let head = input.substring(0, startIndex),
tail = input.substring(startIndex + 1, endIndex);
tree[head] = {};
tail.split(/\s*,\s*/).forEach(token => parseAsKeyMap(token, tree[head]));
} else {
tree[input] = {};
}
return tree;
}
function keyMapToTree(input) {
let keys = Object.keys(input);
if (keys.length !== 1) {
throw new Error('Object must be non-null and have only one key!');
}
let key = keys[0], node = { name: key, generics: [] };
keyMapToTreeInner(input[key], node.generics);
return node;
}
function keyMapToTreeInner(input, nodeArray) {
Object.keys(input).map(key => {
let node = { name: key, generics: [] };
keyMapToTreeInner(input[key], node.generics);
nodeArray.push(node)
});
}
.as-console-wrapper {
top: 0;
max-height: 100% !important;
}
<!--
The initial key-map will look like this, so convert this structure to a tree.
{
"Foo": {
"Bar": {},
"Baz": {
"Qux": {}
}
}
}
-->
添加回答
举报