From 27f695eef5c22a87ad8fdd290eaa61aec4ed7f40 Mon Sep 17 00:00:00 2001 From: Ivan Goncharov Date: Fri, 28 Jun 2019 22:33:25 +0300 Subject: [PATCH] dedent: Simplify and remove unused features (#2000) --- src/jsutils/__tests__/dedent-test.js | 9 ------ src/jsutils/dedent.js | 46 ++++++++++++---------------- 2 files changed, 20 insertions(+), 35 deletions(-) diff --git a/src/jsutils/__tests__/dedent-test.js b/src/jsutils/__tests__/dedent-test.js index 2c306664e4..55591c83c9 100644 --- a/src/jsutils/__tests__/dedent-test.js +++ b/src/jsutils/__tests__/dedent-test.js @@ -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 { diff --git a/src/jsutils/dedent.js b/src/jsutils/dedent.js index 0301f99972..24b07f147a 100644 --- a/src/jsutils/dedent.js +++ b/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. @@ -28,20 +13,29 @@ function fixIndent(str: string): string { * str === "{\n test\n}\n"; */ export default function dedent( - strings: string | Array, + strings: Array, ...values: Array ): 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 }