Skip to content

Commit

Permalink
use segmenter to extract graphemes
Browse files Browse the repository at this point in the history
  • Loading branch information
larsrickert committed Jan 24, 2025
1 parent 44a3a22 commit 8b91bcd
Showing 1 changed file with 17 additions and 4 deletions.
21 changes: 17 additions & 4 deletions packages/sit-onyx/src/utils/strings.ts
Original file line number Diff line number Diff line change
Expand Up @@ -30,13 +30,26 @@ export const getInitials = (username: string, locale: string) => {
return;
}

const segmenter = new Intl.Segmenter(locale, { granularity: "word" });
const wordSegmenter = new Intl.Segmenter(locale, { granularity: "word" });

const name = username.trim().toUpperCase();
const segments = Array.from(segmenter.segment(name));
const wordSegments = Array.from(wordSegmenter.segment(name));
const firstWord = wordSegments[0].segment;
const lastWord = wordSegments.length === 1 ? undefined : wordSegments.at(-1)?.segment;

if (segments.length === 1) return segments[0].segment.substring(0, 2);
return `${segments[0].segment.charAt(0)}${segments.at(-1)?.segment.charAt(0)}`;
if (!lastWord) {
return `${getGrapheme(firstWord, locale, 0)}${getGrapheme(firstWord, locale, 1)}`;
}
return `${getGrapheme(firstWord, locale, 0)}${getGrapheme(lastWord, locale, 0)}`;
};

/**
* Gets the character at tht given index using the `Intl.Segmenter` API.
*/
const getGrapheme = (value: string, locale: string, index: number) => {
const segmenter = new Intl.Segmenter(locale, { granularity: "grapheme" });
const segments = Array.from(segmenter.segment(value)).map((segment) => segment.segment);
return segments.at(index) ?? "";
};

/**
Expand Down

0 comments on commit 8b91bcd

Please sign in to comment.