Skip to content

Commit

Permalink
add countGraphemes()
Browse files Browse the repository at this point in the history
  • Loading branch information
SirPepe committed Nov 26, 2024
1 parent da736c3 commit 969fb64
Show file tree
Hide file tree
Showing 3 changed files with 29 additions and 5 deletions.
7 changes: 6 additions & 1 deletion src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,12 @@ export { isRegExp, escapeRegExpString } from "./regexp";
export { addAll } from "./set";
export { SortedArray } from "./SortedArray";
export { asc, desc } from "./sorting";
export { uppercaseFirst, lowercaseFirst, length } from "./string";
export {
uppercaseFirst,
lowercaseFirst,
length,
countGraphemes,
} from "./string";
export { TrieMap } from "./TrieMap";
export { UnsafeMap } from "./UnsafeMap";
export type {
Expand Down
13 changes: 10 additions & 3 deletions src/string.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,12 +21,19 @@ export function lowercaseFirst(str: string): string {
}

/**
* Get the number of characters in a string with customizable value for tabs.
* Get the number of characters/graphemes in a string.
*/
export function countGraphemes(text: string): number {
return Array.from(new Intl.Segmenter().segment(text)).length;
}

/**
* Get the number of characters/graphemes in a string.
*/
export function length(text: string, tabSize: number): number {
let size = 0;
for (const char of text) {
if (char === "\t") {
for (const { segment } of new Intl.Segmenter().segment(text)) {
if (segment === "\t") {
size += tabSize;
} else {
size++;
Expand Down
14 changes: 13 additions & 1 deletion test/string.test.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,9 @@
import { lowercaseFirst, uppercaseFirst, length } from "../src/string";
import {
lowercaseFirst,
uppercaseFirst,
length,
countGraphemes,
} from "../src/string";

describe("String", () => {
describe("capitalizeFirst()", () => {
Expand All @@ -25,4 +30,11 @@ describe("String", () => {
expect(length("Hello\n🤡", 2)).toBe(7);
});
});

describe("countGraphemes()", () => {
it("counts graphemes", () => {
expect(countGraphemes("ABC")).toBe(3);
expect(countGraphemes("Hello\n🤡")).toBe(7);
});
});
});

0 comments on commit 969fb64

Please sign in to comment.