]>
Commit | Line | Data |
---|---|---|
5422a9cc TL |
1 | /** |
2 | * @fileoverview Utilities to operate on strings. | |
3 | * @author Stephen Wade | |
4 | */ | |
5 | ||
6 | "use strict"; | |
7 | ||
f2a92ac6 DC |
8 | //------------------------------------------------------------------------------ |
9 | // Requirements | |
10 | //------------------------------------------------------------------------------ | |
11 | ||
12 | const Graphemer = require("graphemer").default; | |
13 | ||
14 | //------------------------------------------------------------------------------ | |
15 | // Helpers | |
16 | //------------------------------------------------------------------------------ | |
17 | ||
18 | // eslint-disable-next-line no-control-regex -- intentionally including control characters | |
19 | const ASCII_REGEX = /^[\u0000-\u007f]*$/u; | |
20 | ||
21 | /** @type {Graphemer | undefined} */ | |
22 | let splitter; | |
23 | ||
24 | //------------------------------------------------------------------------------ | |
25 | // Public Interface | |
26 | //------------------------------------------------------------------------------ | |
27 | ||
5422a9cc TL |
28 | /** |
29 | * Converts the first letter of a string to uppercase. | |
30 | * @param {string} string The string to operate on | |
31 | * @returns {string} The converted string | |
32 | */ | |
33 | function upperCaseFirst(string) { | |
34 | if (string.length <= 1) { | |
35 | return string.toUpperCase(); | |
36 | } | |
37 | return string[0].toUpperCase() + string.slice(1); | |
38 | } | |
39 | ||
f2a92ac6 DC |
40 | /** |
41 | * Counts graphemes in a given string. | |
42 | * @param {string} value A string to count graphemes. | |
43 | * @returns {number} The number of graphemes in `value`. | |
44 | */ | |
45 | function getGraphemeCount(value) { | |
46 | if (ASCII_REGEX.test(value)) { | |
47 | return value.length; | |
48 | } | |
49 | ||
50 | if (!splitter) { | |
51 | splitter = new Graphemer(); | |
52 | } | |
53 | ||
54 | return splitter.countGraphemes(value); | |
55 | } | |
56 | ||
5422a9cc | 57 | module.exports = { |
f2a92ac6 DC |
58 | upperCaseFirst, |
59 | getGraphemeCount | |
5422a9cc | 60 | }; |