|
| 1 | +/* |
| 2 | + * Copyright (C) 2025 The ORT Server Authors (See <https://github.com/eclipse-apoapsis/ort-server/blob/main/NOTICE>) |
| 3 | + * |
| 4 | + * Licensed under the Apache License, Version 2.0 (the "License"); |
| 5 | + * you may not use this file except in compliance with the License. |
| 6 | + * You may obtain a copy of the License at |
| 7 | + * |
| 8 | + * https://www.apache.org/licenses/LICENSE-2.0 |
| 9 | + * |
| 10 | + * Unless required by applicable law or agreed to in writing, software |
| 11 | + * distributed under the License is distributed on an "AS IS" BASIS, |
| 12 | + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 13 | + * See the License for the specific language governing permissions and |
| 14 | + * limitations under the License. |
| 15 | + * |
| 16 | + * SPDX-License-Identifier: Apache-2.0 |
| 17 | + * License-Filename: LICENSE |
| 18 | + */ |
| 19 | + |
| 20 | +export function extractInitials( |
| 21 | + fullName: string | undefined |
| 22 | +): string | undefined { |
| 23 | + // Remove non-alphanumeric characters. |
| 24 | + const strippedName = (fullName ?? '').replace( |
| 25 | + /[^\p{Letter}\p{Number}\p{Separator}]/gu, |
| 26 | + '' |
| 27 | + ); |
| 28 | + |
| 29 | + // Split words, omitting empty strings. |
| 30 | + const words = strippedName.split(/\p{Separator}/u).filter(Boolean); |
| 31 | + |
| 32 | + const firstName = words.at(0); |
| 33 | + if (!firstName || !firstName[0]) return undefined; |
| 34 | + |
| 35 | + const firstInitial = firstName[0].toUpperCase(); |
| 36 | + if (words.length == 1) return firstInitial; |
| 37 | + |
| 38 | + const lastName = words[words.length - 1]; |
| 39 | + if (!lastName || !lastName[0]) return firstInitial; |
| 40 | + |
| 41 | + const lastInitial = lastName[0].toUpperCase(); |
| 42 | + return firstInitial + lastInitial; |
| 43 | +} |
| 44 | + |
| 45 | +if (import.meta.vitest) { |
| 46 | + const { it, expect } = import.meta.vitest; |
| 47 | + |
| 48 | + it('extractInitials', () => { |
| 49 | + expect(extractInitials('John')).toBe('J'); |
| 50 | + expect(extractInitials('John Doe')).toBe('JD'); |
| 51 | + expect(extractInitials('John A. Doe')).toBe('JD'); |
| 52 | + |
| 53 | + expect(extractInitials('lower case')).toBe('LC'); |
| 54 | + expect(extractInitials('Seven of 9')).toBe('S9'); |
| 55 | + expect(extractInitials('Über ätzend')).toBe('ÜÄ'); |
| 56 | + expect(extractInitials(' with spaces everywhere ')).toBe('WE'); |
| 57 | + |
| 58 | + expect(extractInitials(undefined)).toBe(undefined); |
| 59 | + expect(extractInitials('')).toBe(undefined); |
| 60 | + expect(extractInitials('??')).toBe(undefined); |
| 61 | + }); |
| 62 | +} |
0 commit comments