Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

dedent: Simplify and remove unused features #2000

Merged
merged 1 commit into from Jun 28, 2019
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
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
}