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.
function countUnicodeChars(str: string): number {
let result: number = 0;
for (let i = 0; i < str.length; i++, result++) {
const c: number = str.charCodeAt(i);
if (c < 0xD800 || c >= 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;
}
for (const ch of str) {
const cc = ch.codePointAt(0) as number;
if (0xD800 <= cc && cc < 0xE000)
throw new RangeError("Invalid UTF-16 string");
result++;
}
return result;
}

Loading…
Cancel
Save