/
wordWrap.js
73 lines (60 loc) · 1.65 KB
/
wordWrap.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
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
/* Wrap a string to a given length.
*
* |Name |Desc |
* |------|------------------------------|
* |txt |Text to wrap |
* |width |Text width |
* |return|String wrapped at given length|
*/
/* example
* wordWrap('Licia is a utility library.', 10);
* // -> 'Licia is \na utility \nlibrary.'
*/
/* module
* env: all
* since: 1.27.0
*/
/* typescript
* export declare function wordWrap(txt: string, width: number): string;
*/
_('map reduce concat last trim');
exports = function(txt, width) {
const lines = txt.split('\n');
return map(lines, line => wrap(line, width)).join('\n');
};
const regWordBoundary = /(\S+\s+)/;
function wrap(txt, width) {
const chunks = reduce(
txt.split(regWordBoundary),
(chunks, word) => {
if (trim(word) === '') return chunks;
if (word.length > width) {
chunks = concat(
chunks,
word.match(new RegExp(`.{1,${width}}`, 'g'))
);
} else {
chunks.push(word);
}
return chunks;
},
[]
);
const lines = reduce(
chunks,
(lines, chunk) => {
const lastLine = last(lines);
if (lastLine.length + chunk.length > width) {
if (trim(lastLine) === '') {
lines.pop();
}
lines.push(chunk);
} else {
lines[lines.length - 1] = lastLine + chunk;
}
return lines;
},
[chunks.shift()]
);
return lines.join('\n');
}