3 回答

TA貢獻(xiàn)1772條經(jīng)驗(yàn) 獲得超5個贊
最簡單的方法是遞歸地構(gòu)建一個鍵映射結(jié)構(gòu),然后將其轉(zhuǎn)換為樹。
keyMapToTree下面的函數(shù)使用名為的內(nèi)部幫助器函數(shù)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": {}
}
}
}
-->
添加回答
舉報