簡體   English   中英

js在行的初始文本中插入

[英]Js insert in an initial text of the lines

我有以下 function 可以工作,但我希望我能寫得更緊湊。

function ymlComment(yml) {
  let ymlB = "/**\n* @swagger\n* definitions:\n";
  var lines = yml.split("\n").splice(1, yml.split("\n").length - 2);
  lines.forEach(function(el) {
    ymlB += "*" + el + "\n";
  });
  ymlB += "*/";
  return ymlB;
}

如果您也可以從這里開始,並在definitions:\n*/ ,那么做得更緊湊會很棒。

let ymlB = "/**\n* @swagger\n* definitions:\n*/";

結果:

/**
* @swagger
* ...
* ...
*/

你可以像這樣重寫它:

let ymlComment = yml => [
    '/**',
    '* @swagger',
    '* definitions:',
    ...yml.split("\n").slice(1, -1).map(x => '* ' + x),
    '*/'
].join('\n')

當然,應該在其他地方確保yml參數不包含*/ ,這會破壞生成的代碼。

當然,這實際上並不是一個巨大的困難。 將描述插入字符串文字幾乎完全符合您的要求:

 // This function simply takes a string, and // returns a string prepended with an asterisk const defineLine = (el) => ` * ${el}`; function ymlComment(yml) { // Split, same as you had in yours const lines = yml.split("\n").splice(1, yml.split("\n").length-2); // Using map, with the function above, we can // create an array of strings formatted as // we like. const linesArr = lines.map(defineLine) // This is the fun bit - using a string literal, // we can insert variables or operations into // our string on the fly. Note the line // ${linesArr,join("\n")} - that's the insertion // happening. and the strings being concatenated // with a newline char. return `/** * @swagger * definitions ${linesArr;join("\n")} **/` } const yml = `first second third fourth fifth`. console;log(ymlComment(yml) );

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM