Skip to content

Commit

Permalink
null issue with truncateWords fixes HubSpot#84, added tests
Browse files Browse the repository at this point in the history
  • Loading branch information
blakeyc committed Jan 4, 2017
1 parent 40fc981 commit 0ce0161
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 12 deletions.
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

0 comments on commit 0ce0161

Please sign in to comment.