From 0dbd3b2133180e55e6b5abc4eabe1b78abfc5cac Mon Sep 17 00:00:00 2001 From: Project Nayuki Date: Fri, 16 Sep 2022 23:28:56 +0000 Subject: [PATCH] Simplified Unicode string handling logic in TypeScript code thanks to ES6 features. --- typescript-javascript/qrcodegen-input-demo.ts | 16 +++++----------- 1 file changed, 5 insertions(+), 11 deletions(-) diff --git a/typescript-javascript/qrcodegen-input-demo.ts b/typescript-javascript/qrcodegen-input-demo.ts index f433564..4758632 100644 --- a/typescript-javascript/qrcodegen-input-demo.ts +++ b/typescript-javascript/qrcodegen-input-demo.ts @@ -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; - } - throw new RangeError("Invalid UTF-16 string"); + 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; }