Skip to content

Commit

Permalink
Compact word wrap (partial)
Browse files Browse the repository at this point in the history
  • Loading branch information
speedytwenty committed Mar 31, 2022
1 parent f926678 commit b389c20
Show file tree
Hide file tree
Showing 3 changed files with 35 additions and 3 deletions.
2 changes: 1 addition & 1 deletion src/cell.js
Original file line number Diff line number Diff line change
Expand Up @@ -67,7 +67,7 @@ class Cell {
i++;
}
}
this.lines = utils.colorizeLines(utils.wordWrap(fixedWidth, this.content));
this.lines = utils.colorizeLines(utils.wordWrap(fixedWidth, this.content, tableOptions.wrapWords));
} else {
this.lines = utils.colorizeLines(this.content.split('\n'));
}
Expand Down
24 changes: 22 additions & 2 deletions src/utils.js
Original file line number Diff line number Diff line change
Expand Up @@ -270,11 +270,31 @@ function wordWrap(maxLength, input) {
return lines;
}

function multiLineWordWrap(maxLength, input) {
function wrapWords(maxLength, input) {
let lines = [];
let line = '';
function pushLine(str, ws) {
if (line.length && ws) line += ws;
line += str;
while (line.length > maxLength) {
lines.push(line.slice(0, maxLength));
line = line.slice(maxLength);
}
}
let split = input.split(/(\s+)/g);
for (let i = 0; i < split.length; i += 2) {
pushLine(split[i], i && split[i - 1]);
}
if (line.length) lines.push(line);
return lines;
}

function multiLineWordWrap(maxLength, input, words = false) {
let output = [];
input = input.split('\n');
const handler = words ? wrapWords : wordWrap;
for (let i = 0; i < input.length; i++) {
output.push.apply(output, wordWrap(maxLength, input[i]));
output.push.apply(output, handler(maxLength, input[i]));
}
return output;
}
Expand Down
12 changes: 12 additions & 0 deletions test/utils-test.js
Original file line number Diff line number Diff line change
Expand Up @@ -322,6 +322,18 @@ describe('utils', function () {
let expected = ['\x1b[31m漢字\x1b[0m', ' 漢字'];
expect(wordWrap(5, input)).toEqual(expected);
});

describe('wrapWords', function () {
it('wraps long words', function () {
expect(wordWrap(10, 'abcdefghijklmnopqrstuvwxyz', true)).toEqual(['abcdefghij', 'klmnopqrst', 'uvwxyz']);
expect(wordWrap(10, 'abcdefghijk lmnopqrstuv wxyz', true)).toEqual(['abcdefghij', 'k lmnopqrs', 'tuv wxyz']);
expect(wordWrap(10, 'ab cdefghijk lmnopqrstuv wx yz', true)).toEqual([
'ab cdefghi',
'jk lmnopqr',
'stuv wx yz',
]);
});
});
});

describe('colorizeLines', function () {
Expand Down

0 comments on commit b389c20

Please sign in to comment.