Skip to content

Generate code using JavaScript code

Grégoire Geis edited this page Jan 4, 2022 · 2 revisions

The following script can be used with "Pipe selections":

await run(Selections.map((text) => text.replace(/^\/\/ |START$[\s\S]+?END$/gm, "")));

Before:

// await replace((text) => text.replace(/(\/\/ START\n)([\s\S]+?)(\/\/ END\n)/m, (_, before, after) =>
^
//   before + "const alphabet = " + JSON.stringify(
//     Array.from({ length: 26 }, (_, i) => String.fromCharCode(97 + i)),
//     undefined, 2,
//   ) + "\n" + after);
// START

// END
     ^ 0

After:

// await replace((text) => text.replace(/(\/\/ START\n)([\s\S]+?)(\/\/ END\n)/m, (_, before, after) =>
^
//   before + "const alphabet = " + JSON.stringify(
//     Array.from({ length: 26 }, (_, i) => String.fromCharCode(97 + i)),
//     undefined, 2,
//   ) + ";\n" + after);
// START
const alphabet = [
  "a",
  "b",
  "c",
  "d",
  "e",
  "f",
  "g",
  "h",
  "i",
  "j",
  "k",
  "l",
  "m",
  "n",
  "o",
  "p",
  "q",
  "r",
  "s",
  "t",
  "u",
  "v",
  "w",
  "x",
  "y",
  "z"
];
// END
     ^ 0

To avoid having a placeholder for the insertion in the form of START .. END tags, you may use "Pipe and append":

await run(Selections.map((text) => text.replace(/^\/\/ /gm, ""))[0]);

Before:

// return "const alphabet = " + JSON.stringify(
//   Array.from({ length: 26 }, (_, i) => String.fromCharCode(97 + i)),
//   undefined, 2,
// ) + ";\n";

After:

// return "const alphabet = " + JSON.stringify(
//   Array.from({ length: 26 }, (_, i) => String.fromCharCode(97 + i)),
//   undefined, 2,
// ) + ";\n";
const alphabet = [
  "a",
  "b",
  "c",
  "d",
  "e",
  "f",
  "g",
  "h",
  "i",
  "j",
  "k",
  "l",
  "m",
  "n",
  "o",
  "p",
  "q",
  "r",
  "s",
  "t",
  "u",
  "v",
  "w",
  "x",
  "y",
  "z"
];