第七色在线视频,2021少妇久久久久久久久久,亚洲欧洲精品成人久久av18,亚洲国产精品特色大片观看完整版,孙宇晨将参加特朗普的晚宴

為了賬號安全,請及時綁定郵箱和手機(jī)立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

從字符串中提取泛型類型參數(shù)

從字符串中提取泛型類型參數(shù)

喵喵時光機(jī) 2021-03-29 12:14:55
我想創(chuàng)建一個從類型定義(作為純字符串)提取“泛型類型參數(shù)”的函數(shù)。它應(yīng)該采用這樣的輸入字符串:Foo<Bar, Baz<Qux>>并返回一個具有引用的類型和泛型的對象,類似這樣的東西(當(dāng)然,只要我可以檢索所需的信息,就不必采用這種確切的格式):{   "name": "Foo",   "generics": [      {         "name": "Bar",         "generics": []      },      {         "name": "Baz",         "generics": [            {               "name": "Qux",               "generics": []            }         ]      }   ]}我的猜測是String.match與正則表達(dá)式一起使用,/<.*>/g用逗號作為分隔符分割結(jié)果,然后遞歸地解析每個參數(shù)的泛型。但是,我覺得這太復(fù)雜了,我缺少一種更簡單的方法。
查看完整描述

3 回答

?
月關(guān)寶盒

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

    }

  }

}


-->


查看完整回答
反對 回復(fù) 2021-04-08
  • 3 回答
  • 0 關(guān)注
  • 186 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補(bǔ)貼
聯(lián)系客服咨詢優(yōu)惠詳情

幫助反饋 APP下載

慕課網(wǎng)APP
您的移動學(xué)習(xí)伙伴

公眾號

掃描二維碼
關(guān)注慕課網(wǎng)微信公眾號