11// @flow strict
22
3- import invariant from './invariant' ;
4-
5- /**
6- * fixes indentation by removing leading spaces and tabs from each line
7- */
8- function fixIndent ( str : string ) : string {
9- const trimmedStr = str
10- . replace ( / ^ \n * / m, '' ) // remove leading newline
11- . replace ( / [ \t ] * $ / , '' ) ; // remove trailing spaces and tabs
12- const indentMatch = / ^ [ \t ] * / . exec ( trimmedStr ) ;
13- invariant ( Array . isArray ( indentMatch ) ) ;
14- const indent = indentMatch [ 0 ] ; // figure out indent
15- return trimmedStr . replace ( RegExp ( '^' + indent , 'mg' ) , '' ) ; // remove indent
16- }
17-
183/**
194 * An ES6 string tag that fixes indentation. Also removes leading newlines
205 * and trailing spaces and tabs, but keeps trailing newlines.
@@ -28,20 +13,29 @@ function fixIndent(str: string): string {
2813 * str === "{\n test\n}\n";
2914 */
3015export default function dedent (
31- strings : string | Array < string > ,
16+ strings : Array < string > ,
3217 ...values : Array < string >
3318) : string {
34- // when used as an ordinary function, allow passing a singleton string
35- const strArray = typeof strings === 'string' ? [ strings ] : strings ;
36- const numValues = values . length ;
19+ let str = '' ;
3720
38- const str = strArray . reduce ( ( prev , cur , index ) => {
39- let next = prev + cur ;
40- if ( index < numValues ) {
41- next += values [ index ] ; // interpolation
21+ for ( let i = 0 ; i < strings . length ; ++ i ) {
22+ str += strings [ i ] ;
23+ if ( i < values . length ) {
24+ str += values [ i ] ; // interpolation
4225 }
43- return next ;
44- } , '' ) ;
26+ }
4527
46- return fixIndent ( str ) ;
28+ const trimmedStr = str
29+ . replace ( / ^ \n * / m, '' ) // remove leading newline
30+ . replace ( / [ \t ] * $ / , '' ) ; // remove trailing spaces and tabs
31+
32+ // fixes indentation by removing leading spaces and tabs from each line
33+ let indent = '' ;
34+ for ( const char of trimmedStr ) {
35+ if ( char !== ' ' && char !== '\t' ) {
36+ break ;
37+ }
38+ indent += char ;
39+ }
40+ return trimmedStr . replace ( RegExp ( '^' + indent , 'mg' ) , '' ) ; // remove indent
4741}
0 commit comments