Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 7 additions & 1 deletion __tests__/humanize.spec.js
Original file line number Diff line number Diff line change
Expand Up @@ -193,14 +193,19 @@ describe('Truncating objects to shorter versions', () => {
const objs = {
str: 'abcdefghijklmnopqrstuvwxyz',
num: 1234567890,
arr: [1, 2, 3, 4, 5]
arr: [1, 2, 3, 4, 5],
wrd: 'hello world'
};

it('should truncate a long string with ellipsis', () => {
expect(Humanize.truncate(objs.str, 14)).toEqual('abcdefghijk...');
expect(Humanize.truncate(objs.str, 14, '...kidding')).toEqual('abcd...kidding');
});

it('should truncate a string of words with ellipsis', () => {
expect(Humanize.truncateWords(objs.wrd, 1)).toEqual('hello ...');
});

it('should truncate a number to an upper bound', () => {
expect(Humanize.truncatenumber(objs.num, 500)).toEqual('500+');
expect(Humanize.boundedNumber(objs.num, 500)).toEqual('500+');
Expand All @@ -210,6 +215,7 @@ describe('Truncating objects to shorter versions', () => {
expect(Humanize.truncate(objs.str, objs.str.length + 1)).toEqual(objs.str);
expect(Humanize.truncatenumber(objs.num, objs.num + 1)).toEqual(String(objs.num));
expect(Humanize.boundedNumber(objs.num, objs.num + 1)).toEqual(String(objs.num));
expect(Humanize.truncateWords(objs.wrd, 3)).toEqual('hello world');
});
});

Expand Down
20 changes: 9 additions & 11 deletions src/humanize.js
Original file line number Diff line number Diff line change
Expand Up @@ -287,21 +287,19 @@
// Truncates a string after a certain number of words.
truncateWords(string, length) {
const array = string.split(' ');
let result = '';
let i = 0;

while (i < length) {
if (exists(array[i])) {
result += `${array[i]} `;
}
i++;
}

if (array.length > length) {
let result = '';
let i = 0;
while (i < length) {
if (exists(array[i])) {
result += `${array[i]} `;
}
i++;
}
return `${result}...`;
}

return null;
return string;
},

truncatewords(...args) {
Expand Down