为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

喵喵时光机 2021-03-29 12:14:55
我想创建一个从类型定义(作为纯字符串)提取“泛型类型参数”的函数。它应该采用这样的输入字符串:Foo<Bar, Baz<Qux>>并返回一个具有引用的类型和泛型的对象,类似这样的东西(当然,只要我可以检索所需的信息,就不必采用这种确切的格式):{   "name": "Foo",   "generics": [      {         "name": "Bar",         "generics": []      },      {         "name": "Baz",         "generics": [            {               "name": "Qux",               "generics": []            }         ]      }   ]}我的猜测是String.match与正则表达式一起使用,/<.*>/g用逗号作为分隔符分割结果,然后递归地解析每个参数的泛型。但是,我觉得这太复杂了,我缺少一种更简单的方法。
查看完整描述

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": {}

    }

  }

}


-->


查看完整回答
反对 回复 2021-04-08
  • 3 回答
  • 0 关注
  • 178 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号