2023-01-03 19:55:46 +00:00
|
|
|
// Copyright 2021 Signal Messenger, LLC
|
2021-03-08 22:31:19 +00:00
|
|
|
// SPDX-License-Identifier: AGPL-3.0-only
|
|
|
|
|
2022-10-04 23:17:15 +00:00
|
|
|
import { map, size, take, join } from './iterables';
|
2021-04-07 17:04:42 +00:00
|
|
|
|
|
|
|
export function getGraphemes(str: string): Iterable<string> {
|
|
|
|
const segments = new Intl.Segmenter().segment(str);
|
|
|
|
return map(segments, s => s.segment);
|
|
|
|
}
|
2021-03-31 16:15:49 +00:00
|
|
|
|
2021-03-08 22:31:19 +00:00
|
|
|
export function count(str: string): number {
|
|
|
|
const segments = new Intl.Segmenter().segment(str);
|
2021-03-31 16:15:49 +00:00
|
|
|
return size(segments);
|
2021-03-08 22:31:19 +00:00
|
|
|
}
|
2022-08-22 23:31:35 +00:00
|
|
|
|
2022-10-04 23:17:15 +00:00
|
|
|
/** @return truncated string and size (after any truncation) */
|
|
|
|
export function truncateAndSize(
|
|
|
|
str: string,
|
|
|
|
toSize?: number
|
|
|
|
): [string, number] {
|
|
|
|
const segments = new Intl.Segmenter().segment(str);
|
|
|
|
const originalSize = size(segments);
|
|
|
|
if (toSize === undefined || originalSize <= toSize) {
|
|
|
|
return [str, originalSize];
|
|
|
|
}
|
|
|
|
return [
|
|
|
|
join(
|
|
|
|
map(take(segments, toSize), s => s.segment),
|
|
|
|
''
|
|
|
|
),
|
|
|
|
toSize,
|
|
|
|
];
|
|
|
|
}
|
|
|
|
|
2022-08-22 23:31:35 +00:00
|
|
|
export function isSingleGrapheme(str: string): boolean {
|
|
|
|
if (str === '') {
|
|
|
|
return false;
|
|
|
|
}
|
|
|
|
const segments = new Intl.Segmenter().segment(str);
|
|
|
|
return segments.containing(0).segment === str;
|
|
|
|
}
|