Skip to content

Commit

Permalink
#81 Add utility function to get a string-formatted list of users
Browse files Browse the repository at this point in the history
  • Loading branch information
danielemery committed Nov 26, 2023
1 parent 6cf45dd commit 9c190e3
Show file tree
Hide file tree
Showing 3 changed files with 68 additions and 0 deletions.
35 changes: 35 additions & 0 deletions src/activity/activity.service.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
import { UnhandledError } from '../util/common.errors';
import { ActivityService } from './activity.service';

const sut = new ActivityService();
describe('activity', () => {
describe('activity.service', () => {
describe('userListToString', () => {
it('must throw an error if the user list is empty', () => {
expect(() => sut.userListToString([])).toThrow(UnhandledError);
});
it('must just return the name or email of a single user', () => {
expect(sut.userListToString([{ name: 'John', email: '[email protected]' }])).toEqual('John');
expect(sut.userListToString([{ email: '[email protected]' }])).toEqual('[email protected]');
});
it('must return names separated by & for two users', () => {
expect(
sut.userListToString([
{ name: 'Jack', email: '[email protected]' },
{ name: 'Jill', email: '[email protected]' },
]),
).toEqual('Jack & Jill');
});
it('must return names separated by commas and & for three or more users', () => {
expect(
sut.userListToString([
{ name: 'Jack', email: '[email protected]' },
{ name: 'Jill', email: '[email protected]' },
{ name: 'Bob', email: '[email protected]' },
{ email: '[email protected]' },
]),
).toEqual('Jack, Jill, Bob & [email protected]');
});
});
});
});
32 changes: 32 additions & 0 deletions src/activity/activity.service.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
import { UnhandledError } from '../util/common.errors';

export interface RecentActivityItem {
text: string;
action?: {
name: string;
link: string;
};
}

export class ActivityService {
/**
* Get a formatted string list of users.
* @param users List of userlike objects (contain and email and optionally a name)
* @returns A formatted string list of users.
*/
userListToString(
users: {
name?: string;
email: string;
}[],
) {
if (users.length === 0) {
throw new UnhandledError('Cannot format an empty user list');
}
const names = users.map((user) => user.name ?? user.email);
if (names.length === 1) {
return names[0];
}
return `${names.slice(0, -1).join(', ')} & ${names[names.length - 1]}`;
}
}
1 change: 1 addition & 0 deletions src/util/common.errors.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
export class UnhandledError extends Error {}

0 comments on commit 9c190e3

Please sign in to comment.