forked from maksrom/javascript-nodejs
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathstripIndents.js
More file actions
executable file
·53 lines (39 loc) · 1.24 KB
/
Copy pathstripIndents.js
File metadata and controls
executable file
·53 lines (39 loc) · 1.24 KB
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
51
52
53
function stripFirstEmptyLines(text) {
return text.replace(/^\n+/, ''); // no 'm' flag!
}
// strip first empty lines
function rtrim(text) {
return text.replace(/\s+$/, ''); // no 'm' flag!
}
function rtrimLines(text) {
return text.replace(/[ \t]+$/gim, '');
}
function stripSpaceIndent(text) {
if (!text) return text;
var stripPattern = /^ *(?=\S+)/gm;
var indentLen = text.match(stripPattern)
.reduce(function (min, line) {
return Math.min(min, line.length);
}, Infinity);
var indent = new RegExp('^ {' + indentLen + '}', 'gm');
return indentLen > 0 ? text.replace(indent, '') : text;
}
function stripTabIndent(text) {
if (!text) return text;
var stripPattern = /^\t*(?=\S+)/gm;
var indentLen = text.match(stripPattern)
.reduce(function (min, line) {
return Math.min(min, line.length);
}, Infinity);
var indent = new RegExp('^\t{' + indentLen + '}', 'gm');
return indentLen > 0 ? text.replace(indent, '') : text;
}
// same as Ruby strip_heredoc + rtrim every line + strip first lines and rtrim
module.exports = function(text) {
text = rtrim(text);
text = rtrimLines(text);
text = stripFirstEmptyLines(text);
text = stripSpaceIndent(text);
text = stripTabIndent(text);
return text;
};