-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbreaktext.js
51 lines (47 loc) · 1.09 KB
/
breaktext.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
51
/*global module*/
var chunk = function (tx, callback) {
var prev = 0,
re = /\s/gi,
chunk;
while (re.exec(tx)) {
chunk = tx.slice(prev, re.lastIndex - 1);
callback(chunk);
prev = re.lastIndex - 1;
}
if (prev < tx.length) {
callback(tx.slice(prev));
}
};
module.exports = function (text, limit) {
'use strict';
var lines = [],
currentLine = [],
currentLineLength = 0,
closeLine = function () {
if (currentLineLength) {
lines.push(currentLine.join('').trim());
currentLine = [];
currentLineLength = 0;
}
},
processChunk = function (chunk) {
var index;
if (currentLineLength + chunk.length > limit) {
closeLine();
}
if (chunk.length > limit) {
for (index = 0; index < chunk.length; index += limit) {
processChunk(chunk.slice(index, index + limit));
}
} else {
currentLineLength += chunk.length;
currentLine.push(chunk);
}
};
if (text === '') {
return [''];
}
chunk(text, processChunk);
closeLine();
return lines;
};