blob: e1dd34f829c78db23d54e6398343c89332e2d4a3 (
plain)
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
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
|
/**
* @name string-collapse-leading-whitespace
* @fileoverview Collapse the leading and trailing whitespace of a string
* @version 5.1.0
* @author Roy Revelt, Codsen Ltd
* @license MIT
* {@link https://codsen.com/os/string-collapse-leading-whitespace/}
*/
var version$1 = "5.1.0";
const version = version$1;
function collWhitespace(str, originallineBreakLimit = 1) {
const rawNbsp = "\u00A0";
function reverse(s) {
return Array.from(s).reverse().join("");
}
function prep(whitespaceChunk, limit, trailing) {
const firstBreakChar = trailing ? "\n" : "\r";
const secondBreakChar = trailing ? "\r" : "\n";
if (!whitespaceChunk) {
return whitespaceChunk;
}
let crlfCount = 0;
let res = "";
for (let i = 0, len = whitespaceChunk.length; i < len; i++) {
if (whitespaceChunk[i] === firstBreakChar || whitespaceChunk[i] === secondBreakChar && whitespaceChunk[i - 1] !== firstBreakChar) {
crlfCount++;
}
if (`\r\n`.includes(whitespaceChunk[i]) || whitespaceChunk[i] === rawNbsp) {
if (whitespaceChunk[i] === rawNbsp) {
res += whitespaceChunk[i];
} else if (whitespaceChunk[i] === firstBreakChar) {
if (crlfCount <= limit) {
res += whitespaceChunk[i];
if (whitespaceChunk[i + 1] === secondBreakChar) {
res += whitespaceChunk[i + 1];
i++;
}
}
} else if (whitespaceChunk[i] === secondBreakChar && (!whitespaceChunk[i - 1] || whitespaceChunk[i - 1] !== firstBreakChar) && crlfCount <= limit) {
res += whitespaceChunk[i];
}
} else {
if (!whitespaceChunk[i + 1] && !crlfCount) {
res += " ";
}
}
}
return res;
}
if (typeof str === "string" && str.length) {
let lineBreakLimit = 1;
if (typeof +originallineBreakLimit === "number" && Number.isInteger(+originallineBreakLimit) && +originallineBreakLimit >= 0) {
lineBreakLimit = +originallineBreakLimit;
}
let frontPart = "";
let endPart = "";
if (!str.trim()) {
frontPart = str;
} else if (!str[0].trim()) {
for (let i = 0, len = str.length; i < len; i++) {
if (str[i].trim()) {
frontPart = str.slice(0, i);
break;
}
}
}
if (str.trim() && (str.slice(-1).trim() === "" || str.slice(-1) === rawNbsp)) {
for (let i = str.length; i--;) {
if (str[i].trim()) {
endPart = str.slice(i + 1);
break;
}
}
}
return `${prep(frontPart, lineBreakLimit, false)}${str.trim()}${reverse(prep(reverse(endPart), lineBreakLimit, true))}`;
}
return str;
}
export { collWhitespace, version };
|