Pārlūkot izejas kodu

LibJS: Implement String.prototype.charCodeAt with UTF-16 code units

Timothy Flynn 4 gadi atpakaļ
vecāks
revīzija
48a28a9a73

+ 7 - 4
Userland/Libraries/LibJS/Runtime/StringPrototype.cpp

@@ -145,15 +145,18 @@ JS_DEFINE_NATIVE_FUNCTION(StringPrototype::char_at)
 // 22.1.3.2 String.prototype.charCodeAt ( pos ), https://tc39.es/ecma262/#sec-string.prototype.charcodeat
 JS_DEFINE_NATIVE_FUNCTION(StringPrototype::char_code_at)
 {
-    auto string = ak_string_from(vm, global_object);
-    if (!string.has_value())
+    auto string = utf16_string_from(vm, global_object);
+    if (vm.exception())
         return {};
     auto position = vm.argument(0).to_integer_or_infinity(global_object);
     if (vm.exception())
         return {};
-    if (position < 0 || position >= string->length())
+
+    Utf16View utf16_string_view { string };
+    if (position < 0 || position >= utf16_string_view.length_in_code_units())
         return js_nan();
-    return Value((*string)[position]);
+
+    return Value(utf16_string_view.code_unit_at(position));
 }
 
 // 22.1.3.3 String.prototype.codePointAt ( pos ), https://tc39.es/ecma262/#sec-string.prototype.codepointat

+ 8 - 0
Userland/Libraries/LibJS/Tests/builtins/String/String.prototype.charCodeAt.js

@@ -19,3 +19,11 @@ test("basic functionality", () => {
     expect(s.charCodeAt("foo")).toBe(70);
     expect(s.charCodeAt(undefined)).toBe(70);
 });
+
+test("UTF-16", () => {
+    var s = "😀";
+    expect(s).toHaveLength(2);
+    expect(s.charCodeAt(0)).toBe(0xd83d);
+    expect(s.charCodeAt(1)).toBe(0xde00);
+    expect(s.charCodeAt(2)).toBe(NaN);
+});