* Calculates the byte length of a UTF-8 encoded string * Adapted from https://stackoverflow.com/a/23329386 * @param str - UTF-8 encoded string * @returns byte length of string
(str: string)
| 5 | * @returns byte length of string |
| 6 | */ |
| 7 | function byteLengthUtf8(str: string): number { |
| 8 | let byteLength = str.length |
| 9 | for (let i = str.length - 1; i >= 0; i--) { |
| 10 | const code = str.charCodeAt(i) |
| 11 | if (code > 0x7f && code <= 0x7ff) byteLength++ |
| 12 | else if (code > 0x7ff && code <= 0xffff) byteLength += 2 |
| 13 | if (code >= 0xdc00 && code <= 0xdfff) i-- // trail surrogate |
| 14 | } |
| 15 | return byteLength |
| 16 | } |
| 17 | |
| 18 | export { byteLengthUtf8 } |
no outgoing calls
no test coverage detected