a collection of lightweight TypeScript packages for AT Protocol, the protocol powering Bluesky
atproto bluesky typescript npm
101
fork

Configure Feed

Select the types of activity you want to include in your feed.

feat(util-text): add isGraphemeLengthInRange function

Mary 2aee780c a60d862f

+65
+5
.changeset/fair-garlics-tickle.md
··· 1 + --- 2 + "@atcute/util-text": minor 3 + --- 4 + 5 + add isGraphemeLengthInRange function
+25
packages/misc/util-text/lib/index.rn.ts
··· 8 8 export const getGraphemeLength = (text: string): number => { 9 9 return countGraphemes(text); 10 10 }; 11 + 12 + /** 13 + * checks if the grapheme length of a string is within the specified range 14 + * @param text string to check 15 + * @param min minimum grapheme length (inclusive) 16 + * @param max maximum grapheme length (inclusive) 17 + * @returns true if the grapheme length is within range 18 + */ 19 + export const isGraphemeLengthInRange = (text: string, min: number, max: number): boolean => { 20 + const utf16Len = text.length; 21 + 22 + // UTF-16 length < min means grapheme count < min 23 + if (utf16Len < min) { 24 + return false; 25 + } 26 + 27 + // if there's no minimum constraint and UTF-16 length is within max, 28 + // grapheme count is definitely within max 29 + if (min === 0 && utf16Len <= max) { 30 + return true; 31 + } 32 + 33 + const count = countGraphemes(text); 34 + return count >= min && count <= max; 35 + };
+35
packages/misc/util-text/lib/index.ts
··· 15 15 16 16 return count; 17 17 }; 18 + 19 + /** 20 + * checks if the grapheme length of a string is within the specified range 21 + * @param text string to check 22 + * @param min minimum grapheme length (inclusive) 23 + * @param max maximum grapheme length (inclusive) 24 + * @returns true if the grapheme length is within range 25 + */ 26 + export const isGraphemeLengthInRange = (text: string, min: number, max: number): boolean => { 27 + const utf16Len = text.length; 28 + 29 + // UTF-16 length < min means grapheme count < min 30 + if (utf16Len < min) { 31 + return false; 32 + } 33 + 34 + // if there's no minimum constraint and UTF-16 length is within max, 35 + // grapheme count is definitely within max 36 + if (min === 0 && utf16Len <= max) { 37 + return true; 38 + } 39 + 40 + // count graphemes with early termination 41 + const iterator = segmenter.segment(text)[Symbol.iterator](); 42 + let count = 0; 43 + 44 + while (!iterator.next().done) { 45 + count++; 46 + if (count > max) { 47 + return false; 48 + } 49 + } 50 + 51 + return count >= min; 52 + };