[英]Js insert in an initial text of the lines
I have the following function that works, but I wish I could write it more compactly.我有以下 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;
}
If you could also start from this, and insert the text between definitions:\n
and */
, to do it even more compact would be great.如果您也可以从这里开始,并在
definitions:\n
和*/
,那么做得更紧凑会很棒。
let ymlB = "/**\n* @swagger\n* definitions:\n*/";
Result:结果:
/**
* @swagger
* ...
* ...
*/
You can rewrite it like this:你可以像这样重写它:
let ymlComment = yml => [
'/**',
'* @swagger',
'* definitions:',
...yml.split("\n").slice(1, -1).map(x => '* ' + x),
'*/'
].join('\n')
Of course, it should be ensured elsewhere that the yml
param doesn't contain */
, which would break the generated code.当然,应该在其他地方确保
yml
参数不包含*/
,这会破坏生成的代码。
Sure, that's actually not a huge difficulty.当然,这实际上并不是一个巨大的困难。 Inserting the description into a String Literal would do pretty much exactly what you're asking:
将描述插入字符串文字几乎完全符合您的要求:
// 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.