UNPKG

1.25 kBJavaScriptView Raw
1'use strict';
2
3Object.defineProperty(exports, "__esModule", {
4 value: true
5});
6exports.default = dedent;
7/**
8 * Copyright (c) 2017-present, Facebook, Inc.
9 *
10 * This source code is licensed under the MIT license found in the
11 * LICENSE file in the root directory of this source tree.
12 *
13 *
14 */
15
16/**
17 * fixes identation by removing leading spaces from each line
18 */
19function fixIdent(str) {
20 var indent = /^\n?( *)/.exec(str)[1]; // figure out ident
21 return str.replace(RegExp('^' + indent, 'mg'), '') // remove ident
22 .replace(/^\n*/m, '') // remove leading newline
23 .replace(/ *$/, ''); // remove trailing spaces
24}
25
26/**
27 * An ES6 string tag that fixes identation. Also removes leading newlines
28 * but keeps trailing ones
29 *
30 * Example usage:
31 * const str = dedent`
32 * {
33 * test
34 * }
35 * `
36 * str === "{\n test\n}\n";
37 */
38function dedent(strings) {
39 var raw = typeof strings === 'string' ? [strings] : strings.raw;
40 var res = '';
41 // interpolation
42 for (var i = 0; i < raw.length; i++) {
43 res += raw[i].replace(/\\`/g, '`'); // handle escaped backticks
44
45 if (i < (arguments.length <= 1 ? 0 : arguments.length - 1)) {
46 res += arguments.length <= i + 1 ? undefined : arguments[i + 1];
47 }
48 }
49
50 return fixIdent(res);
51}
\No newline at end of file