1
1
// @flow strict
2
2
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
-
18
3
/**
19
4
* An ES6 string tag that fixes indentation. Also removes leading newlines
20
5
* and trailing spaces and tabs, but keeps trailing newlines.
@@ -28,20 +13,29 @@ function fixIndent(str: string): string {
28
13
* str === "{\n test\n}\n";
29
14
*/
30
15
export default function dedent (
31
- strings : string | Array < string > ,
16
+ strings : Array < string > ,
32
17
...values : Array < string >
33
18
) : 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 = '' ;
37
20
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
42
25
}
43
- return next ;
44
- } , '' ) ;
26
+ }
45
27
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
47
41
}
0 commit comments