Skip to content

Commit 27f695e

Browse files
dedent: Simplify and remove unused features (#2000)
1 parent 7c20807 commit 27f695e

File tree

2 files changed

+20
-35
lines changed

2 files changed

+20
-35
lines changed

src/jsutils/__tests__/dedent-test.js

Lines changed: 0 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -59,15 +59,6 @@ describe('dedent', () => {
5959
);
6060
});
6161

62-
it('also works as an ordinary function on strings', () => {
63-
const output = dedent(`
64-
type Query {
65-
me: User
66-
}
67-
`);
68-
expect(output).to.equal(['type Query {', ' me: User', '}', ''].join('\n'));
69-
});
70-
7162
it('also removes indentation using tabs', () => {
7263
const output = dedent`
7364
\t\t type Query {

src/jsutils/dedent.js

Lines changed: 20 additions & 26 deletions
Original file line numberDiff line numberDiff line change
@@ -1,20 +1,5 @@
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
*/
3015
export 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

Comments
 (0)