简体   繁体   中英

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 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.

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.

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) );

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM