UNPKG

1.79 kBJavaScriptView Raw
1"use strict";
2
3Object.defineProperty(exports, "__esModule", {
4 value: true
5});
6exports.default = dedent;
7
8var _invariant = _interopRequireDefault(require("./invariant"));
9
10function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
11
12/**
13 * Copyright (c) 2017-present, Facebook, Inc.
14 *
15 * This source code is licensed under the MIT license found in the
16 * LICENSE file in the root directory of this source tree.
17 *
18 * strict
19 */
20
21/**
22 * fixes indentation by removing leading spaces and tabs from each line
23 */
24function fixIndent(str) {
25 var trimmedStr = str.replace(/^\n*/m, '') // remove leading newline
26 .replace(/[ \t]*$/, ''); // remove trailing spaces and tabs
27
28 var indentMatch = /^[ \t]*/.exec(trimmedStr);
29 !Array.isArray(indentMatch) ? (0, _invariant.default)(0) : void 0;
30 var indent = indentMatch[0]; // figure out indent
31
32 return trimmedStr.replace(RegExp('^' + indent, 'mg'), ''); // remove indent
33}
34/**
35 * An ES6 string tag that fixes indentation. Also removes leading newlines
36 * and trailing spaces and tabs, but keeps trailing newlines.
37 *
38 * Example usage:
39 * const str = dedent`
40 * {
41 * test
42 * }
43 * `;
44 * str === "{\n test\n}\n";
45 */
46
47
48function dedent(strings) {
49 for (var _len = arguments.length, values = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
50 values[_key - 1] = arguments[_key];
51 }
52
53 // when used as an ordinary function, allow passing a singleton string
54 var strArray = typeof strings === 'string' ? [strings] : strings;
55 var numValues = values.length;
56 var str = strArray.reduce(function (prev, cur, index) {
57 var next = prev + cur;
58
59 if (index < numValues) {
60 next += values[index]; // interpolation
61 }
62
63 return next;
64 }, '');
65 return fixIndent(str);
66}
\No newline at end of file