dedent.js.flow 983 B

1234567891011121314151617181920212223242526272829303132333435363738394041
  1. // @flow strict
  2. /**
  3. * An ES6 string tag that fixes indentation. Also removes leading newlines
  4. * and trailing spaces and tabs, but keeps trailing newlines.
  5. *
  6. * Example usage:
  7. * const str = dedent`
  8. * {
  9. * test
  10. * }
  11. * `;
  12. * str === "{\n test\n}\n";
  13. */
  14. export default function dedent(
  15. strings: $ReadOnlyArray<string>,
  16. ...values: $ReadOnlyArray<string>
  17. ): string {
  18. let str = '';
  19. for (let i = 0; i < strings.length; ++i) {
  20. str += strings[i];
  21. if (i < values.length) {
  22. str += values[i]; // interpolation
  23. }
  24. }
  25. const trimmedStr = str
  26. .replace(/^\n*/m, '') // remove leading newline
  27. .replace(/[ \t]*$/, ''); // remove trailing spaces and tabs
  28. // fixes indentation by removing leading spaces and tabs from each line
  29. let indent = '';
  30. for (const char of trimmedStr) {
  31. if (char !== ' ' && char !== '\t') {
  32. break;
  33. }
  34. indent += char;
  35. }
  36. return trimmedStr.replace(RegExp('^' + indent, 'mg'), ''); // remove indent
  37. }