forked from dmnd/dedent
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdedent.js
50 lines (44 loc) · 1.24 KB
/
dedent.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
// @flow
export default function dedent(
strings: string | Array<string>,
...values: Array<string>
) {
// $FlowFixMe: Flow doesn't undestand .raw
const raw = typeof strings === "string" ? [strings] : strings.raw;
// first, perform interpolation
let result = "";
for (let i = 0; i < raw.length; i++) {
result += raw[i]
// join lines when there is a suppressed newline
.replace(/\\\n[ \t]*/g, "")
// handle escaped backticks
.replace(/\\`/g, "`");
if (i < values.length) {
result += values[i];
}
}
// now strip indentation
const lines = result.split("\n");
let mindent: number | null = null;
lines.forEach(l => {
let m = l.match(/^(\s+)\S+/);
if (m) {
let indent = m[1].length;
if (!mindent) {
// this is the first indented line
mindent = indent;
} else {
mindent = Math.min(mindent, indent);
}
}
});
if (mindent !== null) {
const m = mindent; // appease Flow
result = lines.map(l => l[0] === " " ? l.slice(m) : l).join("\n");
}
return result
// dedent eats leading and trailing whitespace too
.trim()
// handle escaped newlines at the end to ensure they don't get stripped too
.replace(/\\n/g, "\n");
}