DeindentTemplateLiteralString

Exports a simple function that can be passed a template literal. It strips code indentation from it while preserving intended indentation, by stripping out the smallest indent every line has in common.

Tento skript by neměl být instalován přímo. Jedná se o knihovnu, kterou by měly jiné skripty využívat pomocí meta příkazu // @require https://update.greatest.deepsurf.us/scripts/511046/1460584/DeindentTemplateLiteralString.js

  1. // ==UserScript==
  2. // @name DeindentTemplateLiteralString
  3. // @license Unlicense
  4. // @namespace 1N07
  5. // @match *://*/*
  6. // @version 1.2
  7. // @author 1N07
  8. // @description Exports a simple function that can be passed a template literal. It strips code indentation from it while preserving intended indentation, by stripping out the smallest indent every line has in common.
  9. // ==/UserScript==
  10.  
  11. /**
  12. * Takes a string (usually evaluated from a template literal) and strips code indentation from it,
  13. * while preserving intended intendation, by slicing out the smallest indentation each line has in common.
  14. * @param {String} str
  15. * @returns str with code indentation removed
  16. */
  17. function DeindentTemplateLiteralString(str) {
  18. const smallestIndent = Math.min(
  19. ...str
  20. .split("\n")
  21. .filter((line) => line.trim())
  22. .map((line) => line.match(/^\s+/)?.[0]?.length),
  23. );
  24. return str
  25. .split("\n")
  26. .map((line) => line.slice(smallestIndent))
  27. .join("\n")
  28. .trim();
  29. }
  30.  
  31. //aliases
  32. const Deindent = DeindentTemplateLiteralString;