Skip to content

Commit

Permalink
feat: shortenName - DEV-34
Browse files Browse the repository at this point in the history
  • Loading branch information
leomotors committed Jan 16, 2025
1 parent 6c67f9a commit d9b0121
Show file tree
Hide file tree
Showing 2 changed files with 38 additions and 4 deletions.
15 changes: 15 additions & 0 deletions packages/utils/src/name.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,4 +5,19 @@ import { getShortenName } from './name.js'
test('getShortenName', () => {
expect(getShortenName('John Doe')).toBe('John D.')
expect(getShortenName('John Doe Jr.')).toBe('John J.')

// Middle Name Google Style
expect(getShortenName('John [Smith] Doe')).toBe('John D.')
expect(getShortenName('John[Smith] Doe')).toBe('John D.')

// Some edge cases
expect(getShortenName('John')).toBe('John')
expect(getShortenName('John ')).toBe('John')
expect(getShortenName('John Doe ')).toBe('John D.')

// Some edge cases (real)
expect(getShortenName('6531234521 6531234521')).toBe('6531234521')

// Thai
expect(getShortenName('ประยุทธ์ จันทร์โอชา')).toBe('ประยุทธ์ จ.')
})
27 changes: 23 additions & 4 deletions packages/utils/src/name.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,25 @@
export function getShortenName(fullName: string) {
const names = fullName.split(' ')
const firstName = names[0]
const lastName = names[names.length - 1]
// TDD By ChatGPT
export function getShortenName(fullName: string): string {
// Remove text inside square brackets (including brackets themselves)
const sanitized = fullName.replace(/\[.*?\]/g, '').trim()

// Split the sanitized name into parts
const parts = sanitized.split(/\s+/)

if (parts.length < 2) {
// If there's only one part, return it as is (optional, depending on requirements)
return parts[0] || ''
}

// Extract first name and last name (or last relevant part)
const firstName = parts[0]
const lastName = parts[parts.length - 1]

if (firstName === lastName) {
// If first name is the same as last name, return first name only
return firstName
}

// Return first name and abbreviated last name
return `${firstName} ${lastName.charAt(0)}.`
}

0 comments on commit d9b0121

Please sign in to comment.