Skip to content
This repository was archived by the owner on Nov 29, 2022. It is now read-only.

Commit eb1fbb4

Browse files
tillprochaskaRosencrantz
authored andcommitted
Add wrapLines helper
This helper break long lines into an array of lines where no line is longer than the given maximum line length. It’s a very naive implementation that split lines into words/tokens at whitespace and adds tokens to the current line greedily. It would likely produce suboptimal solutions when used with long paragraphs of text or wider lines. Neither is the case for us, so I think we’d be good to go with this instead of pulling in an additional dependency or implementing something more sophisticated.
1 parent 23796dd commit eb1fbb4

File tree

3 files changed

+44
-0
lines changed

3 files changed

+44
-0
lines changed
Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
11
export * from './filterVerticesByText'
22
export * from './interactionModes'
33
export * from './exportSvg'
4+
export * from './wrapLines';
Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
import { wrapLines } from './wrapLines';
2+
3+
describe('wrapLines', () => {
4+
it('doesnt break text shorter than maximum line length', () => {
5+
const lines = wrapLines('a very short line', 25);
6+
expect(lines).toEqual(['a very short line']);
7+
});
8+
9+
it('breaks text longer than maximum line length', () => {
10+
const lines = wrapLines('a very very very very long line', 25);
11+
expect(lines).toEqual([
12+
'a very very very very',
13+
'long line',
14+
]);
15+
});
16+
17+
it('breaks lines after punctuation', () => {
18+
const lines = wrapLines('This is the 1st sentence. And this is the 2nd sentence.', 25);
19+
expect(lines).toEqual([
20+
'This is the 1st sentence.',
21+
'And this is the 2nd',
22+
'sentence.',
23+
]);
24+
});
25+
});
Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
export function wrapLines(text: string, maxLength: number): string[] {
2+
const words = text.split(/\s/);
3+
const lines = [];
4+
let currentLine = [];
5+
6+
for (const word of words) {
7+
if ([...currentLine, word].join(' ').length > maxLength) {
8+
lines.push(currentLine);
9+
currentLine = [];
10+
}
11+
12+
currentLine.push(word);
13+
}
14+
15+
lines.push(currentLine);
16+
17+
return lines.map(line => line.join(' '));
18+
}

0 commit comments

Comments
 (0)