-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdedent.js
46 lines (36 loc) · 1.18 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
// Source code from https://github.com/MartinKolarik/dedent-js
module.exports = function dedent(templateStrings, ...values) {
let matches = [];
let strings =
typeof templateStrings === "string"
? [templateStrings]
: templateStrings.slice();
// 1. Remove trailing whitespace.
strings[strings.length - 1] = strings[strings.length - 1].replace(
/\r?\n([\t ]*)$/,
""
);
// 2. Find all line breaks to determine the highest common indentation level.
for (let i = 0; i < strings.length; i++) {
let match;
if ((match = strings[i].match(/\n[\t ]+/g))) {
matches.push(...match);
}
}
// 3. Remove the common indentation from all strings.
if (matches.length) {
let size = Math.min(...matches.map((value) => value.length - 1));
let pattern = new RegExp(`\n[\t ]{${size}}`, "g");
for (let i = 0; i < strings.length; i++) {
strings[i] = strings[i].replace(pattern, "\n");
}
}
// 4. Remove leading whitespace.
strings[0] = strings[0].replace(/^\r?\n/, "");
// 5. Perform interpolation.
let string = strings[0];
for (let i = 0; i < values.length; i++) {
string += values[i] + strings[i + 1];
}
return string;
};