Skip to content

Commit

Permalink
chore: refactor abridgeErrorMessage
Browse files Browse the repository at this point in the history
  • Loading branch information
Dar Malovani committed Jul 23, 2020
1 parent f8cd885 commit 640679f
Show file tree
Hide file tree
Showing 2 changed files with 11 additions and 5 deletions.
9 changes: 5 additions & 4 deletions src/lib/error-format.ts
Original file line number Diff line number Diff line change
@@ -1,12 +1,13 @@
export function abridgeErrorMessage(
msg: string,
maxLen: number,
ellipsis?: string,
ellipsis = ' ... ',
): string {
if (msg.length <= maxLen) {
return msg;
}
const e = ellipsis || ' ... ';
const toKeep = (maxLen - e.length) / 2;
return msg.slice(0, toKeep) + e + msg.slice(msg.length - toKeep, msg.length);
const toKeep = Math.floor((maxLen - ellipsis.length) / 2);
return (
msg.slice(0, toKeep) + ellipsis + msg.slice(msg.length - toKeep, msg.length)
);
}
7 changes: 6 additions & 1 deletion test/error-format.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,9 +14,14 @@ test('abridge same length as max length', async (t) => {
});

test('abridge longer than max length', async (t) => {
t.equal(abridgeErrorMessage('hello there', 10), 'he ... ere');
t.equal(abridgeErrorMessage('hello there', 10), 'he ... re');
});

test('abridge longer than max length (custom ellipsis)', async (t) => {
t.equal(abridgeErrorMessage('hello there', 10, '--'), 'hell--here');
});

test('abridge is not longer than max length', async (t) => {
const maxLength = 10;
t.true(abridgeErrorMessage('hello there', maxLength).length < maxLength);
});

0 comments on commit 640679f

Please sign in to comment.