Simplified Unicode string handling logic in TypeScript code thanks to ES6 features.

pull/160/head
Project Nayuki 2 years ago
parent 942f4319a6
commit 0dbd3b2133

@ -127,17 +127,11 @@ namespace app {
// Returns the number of Unicode code points in the given UTF-16 string. // Returns the number of Unicode code points in the given UTF-16 string.
function countUnicodeChars(str: string): number { function countUnicodeChars(str: string): number {
let result: number = 0; let result: number = 0;
for (let i = 0; i < str.length; i++, result++) { for (const ch of str) {
const c: number = str.charCodeAt(i); const cc = ch.codePointAt(0) as number;
if (c < 0xD800 || c >= 0xE000) if (0xD800 <= cc && cc < 0xE000)
continue;
else if (0xD800 <= c && c < 0xDC00 && i + 1 < str.length) { // High surrogate
i++;
const d: number = str.charCodeAt(i);
if (0xDC00 <= d && d < 0xE000) // Low surrogate
continue;
}
throw new RangeError("Invalid UTF-16 string"); throw new RangeError("Invalid UTF-16 string");
result++;
} }
return result; return result;
} }

Loading…
Cancel
Save