从字符串中提取泛型类型参数

我想创建一个从类型定义(作为纯字符串)提取“泛型类型参数”的函数。


它应该采用这样的输入字符串:


Foo<Bar, Baz<Qux>>

并返回一个具有引用的类型和泛型的对象,类似这样的东西(当然,只要我可以检索所需的信息,就不必采用这种确切的格式):


{

   "name": "Foo",

   "generics": [

      {

         "name": "Bar",

         "generics": []

      },


      {

         "name": "Baz",

         "generics": [

            {

               "name": "Qux",

               "generics": []

            }

         ]

      }

   ]

}

我的猜测是String.match与正则表达式一起使用,/<.*>/g用逗号作为分隔符分割结果,然后递归地解析每个参数的泛型。但是,我觉得这太复杂了,我缺少一种更简单的方法。


喵喵时光机
浏览 179回答 3
3回答

月关宝盒

最简单的方法是递归地构建一个键映射结构,然后将其转换为树。keyMapToTree下面的函数使用名为的内部帮助器函数keyMapToTreeInner。console.log(keyMapToTree(parseAsKeyMap('Foo<Bar, Baz<Qux>>')));function parseAsKeyMap(input, tree = {}) {&nbsp; input = input.trim();&nbsp; let startIndex = input.indexOf('<'),&nbsp; &nbsp; endIndex&nbsp; &nbsp;= input.lastIndexOf('>');&nbsp; if (startIndex !== -1 && endIndex === -1) {&nbsp; &nbsp; throw new Error("Missing closing bracket '>' for " + input);&nbsp; } else if (startIndex === -1 && endIndex !== -1) {&nbsp; &nbsp; throw new Error("Missing opening bracket '<' for " + input);&nbsp; } else if (startIndex !== -1 && endIndex !== -1) {&nbsp; &nbsp; let head = input.substring(0, startIndex),&nbsp; &nbsp; &nbsp; tail = input.substring(startIndex + 1, endIndex);&nbsp; &nbsp; tree[head] = {};&nbsp; &nbsp; tail.split(/\s*,\s*/).forEach(token => parseAsKeyMap(token, tree[head]));&nbsp; } else {&nbsp; &nbsp; tree[input] = {};&nbsp; }&nbsp; return tree;}function keyMapToTree(input) {&nbsp; let keys = Object.keys(input);&nbsp; if (keys.length !== 1) {&nbsp; &nbsp; throw new Error('Object must be non-null and have only one key!');&nbsp; }&nbsp; let key = keys[0], node = { name: key, generics: [] };&nbsp; keyMapToTreeInner(input[key], node.generics);&nbsp; return node;}function keyMapToTreeInner(input, nodeArray) {&nbsp; Object.keys(input).map(key => {&nbsp; &nbsp; let node = { name: key, generics: [] };&nbsp; &nbsp; keyMapToTreeInner(input[key], node.generics);&nbsp; &nbsp; nodeArray.push(node)&nbsp; });}.as-console-wrapper {&nbsp; top: 0;&nbsp; max-height: 100% !important;}<!--The initial key-map will look like this, so convert this structure to a tree.{&nbsp; "Foo": {&nbsp; &nbsp; "Bar": {},&nbsp; &nbsp; "Baz": {&nbsp; &nbsp; &nbsp; "Qux": {}&nbsp; &nbsp; }&nbsp; }}-->
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript