(strings: TemplateStringsArray, ...values: any[])
| 7 | // 2. Preserve whitespace inside backtick string literals |
| 8 | |
| 9 | export function dedent(strings: TemplateStringsArray, ...values: any[]): string { |
| 10 | const raw = typeof strings === 'string' ? [strings] : strings.raw; |
| 11 | |
| 12 | // first, perform interpolation |
| 13 | let result = ''; |
| 14 | for (let i = 0; i < raw.length; i++) { |
| 15 | result += raw[i] |
| 16 | // join lines when there is a suppressed newline |
| 17 | .replace(/\\\n[ \t]*/g, '') |
| 18 | // handle escaped backticks |
| 19 | .replace(/\\`/g, '`'); |
| 20 | |
| 21 | if (i < values.length) { |
| 22 | result += values[i]; |
| 23 | } |
| 24 | } |
| 25 | |
| 26 | // now strip indentation |
| 27 | const lines = split(result); |
| 28 | let mindent: number | null = null; |
| 29 | lines.forEach((l) => { |
| 30 | let m = l.match(/^(\s+)\S+/); |
| 31 | if (m) { |
| 32 | let indent = m[1].length; |
| 33 | if (!mindent) { |
| 34 | // this is the first indented line |
| 35 | mindent = indent; |
| 36 | } else { |
| 37 | mindent = Math.min(mindent, indent); |
| 38 | } |
| 39 | } |
| 40 | }); |
| 41 | |
| 42 | if (mindent !== null) { |
| 43 | const m = mindent; |
| 44 | result = lines.map((l) => (l[0] === ' ' ? l.slice(m) : l)).join('\n'); |
| 45 | } |
| 46 | |
| 47 | // trim trailing whitespace on all lines |
| 48 | result = result |
| 49 | .split('\n') |
| 50 | .map((l) => l.trimEnd()) |
| 51 | .join('\n'); |
| 52 | |
| 53 | return ( |
| 54 | result |
| 55 | // dedent eats leading and trailing whitespace too |
| 56 | .trim() |
| 57 | // handle escaped newlines at the end to ensure they don't get stripped too |
| 58 | .replace(/\\n/g, '\n') |
| 59 | ); |
| 60 | } |
| 61 | |
| 62 | /** |
| 63 | * Splits a string by newlines. |
no test coverage detected