Skip to content

Commit

Permalink
dedent: Simplify and remove unused features (#2000)
Browse files Browse the repository at this point in the history
  • Loading branch information
IvanGoncharov committed Jun 28, 2019
1 parent 7c20807 commit 27f695e
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 35 deletions.
9 changes: 0 additions & 9 deletions src/jsutils/__tests__/dedent-test.js
Expand Up @@ -59,15 +59,6 @@ describe('dedent', () => {
);
});

it('also works as an ordinary function on strings', () => {
const output = dedent(`
type Query {
me: User
}
`);
expect(output).to.equal(['type Query {', ' me: User', '}', ''].join('\n'));
});

it('also removes indentation using tabs', () => {
const output = dedent`
\t\t type Query {
Expand Down
46 changes: 20 additions & 26 deletions src/jsutils/dedent.js
@@ -1,20 +1,5 @@
// @flow strict

import invariant from './invariant';

/**
* fixes indentation by removing leading spaces and tabs from each line
*/
function fixIndent(str: string): string {
const trimmedStr = str
.replace(/^\n*/m, '') // remove leading newline
.replace(/[ \t]*$/, ''); // remove trailing spaces and tabs
const indentMatch = /^[ \t]*/.exec(trimmedStr);
invariant(Array.isArray(indentMatch));
const indent = indentMatch[0]; // figure out indent
return trimmedStr.replace(RegExp('^' + indent, 'mg'), ''); // remove indent
}

/**
* An ES6 string tag that fixes indentation. Also removes leading newlines
* and trailing spaces and tabs, but keeps trailing newlines.
Expand All @@ -28,20 +13,29 @@ function fixIndent(str: string): string {
* str === "{\n test\n}\n";
*/
export default function dedent(
strings: string | Array<string>,
strings: Array<string>,
...values: Array<string>
): string {
// when used as an ordinary function, allow passing a singleton string
const strArray = typeof strings === 'string' ? [strings] : strings;
const numValues = values.length;
let str = '';

const str = strArray.reduce((prev, cur, index) => {
let next = prev + cur;
if (index < numValues) {
next += values[index]; // interpolation
for (let i = 0; i < strings.length; ++i) {
str += strings[i];
if (i < values.length) {
str += values[i]; // interpolation
}
return next;
}, '');
}

return fixIndent(str);
const trimmedStr = str
.replace(/^\n*/m, '') // remove leading newline
.replace(/[ \t]*$/, ''); // remove trailing spaces and tabs

// fixes indentation by removing leading spaces and tabs from each line
let indent = '';
for (const char of trimmedStr) {
if (char !== ' ' && char !== '\t') {
break;
}
indent += char;
}
return trimmedStr.replace(RegExp('^' + indent, 'mg'), ''); // remove indent
}

0 comments on commit 27f695e

Please sign in to comment.