Przeglądaj źródła

LibJS: Implement String.prototype.charCodeAt

It's broken for strings with characters outside 7-bit ASCII, but
it's broken in the same way as several existing functions (e.g.
charAt()), so that's probably ok for now.
Nico Weber 5 lat temu
rodzic
commit
979e02c0a8

+ 17 - 0
Libraries/LibJS/Runtime/StringPrototype.cpp

@@ -72,6 +72,7 @@ void StringPrototype::initialize(Interpreter& interpreter, GlobalObject& global_
 
     define_native_property("length", length_getter, nullptr, 0);
     define_native_function("charAt", char_at, 1, attr);
+    define_native_function("charCodeAt", char_code_at, 1, attr);
     define_native_function("repeat", repeat, 1, attr);
     define_native_function("startsWith", starts_with, 1, attr);
     define_native_function("indexOf", index_of, 1, attr);
@@ -111,6 +112,22 @@ JS_DEFINE_NATIVE_FUNCTION(StringPrototype::char_at)
     return js_string(interpreter, string.substring(index, 1));
 }
 
+JS_DEFINE_NATIVE_FUNCTION(StringPrototype::char_code_at)
+{
+    auto string = ak_string_from(interpreter, global_object);
+    if (string.is_null())
+        return {};
+    i32 index = 0;
+    if (interpreter.argument_count()) {
+        index = interpreter.argument(0).to_i32(interpreter);
+        if (interpreter.exception())
+            return {};
+    }
+    if (index < 0 || index >= static_cast<i32>(string.length()))
+        return js_nan();
+    return Value((i32)string[index]);
+}
+
 JS_DEFINE_NATIVE_FUNCTION(StringPrototype::repeat)
 {
     auto string = ak_string_from(interpreter, global_object);

+ 1 - 0
Libraries/LibJS/Runtime/StringPrototype.h

@@ -40,6 +40,7 @@ public:
 
 private:
     JS_DECLARE_NATIVE_FUNCTION(char_at);
+    JS_DECLARE_NATIVE_FUNCTION(char_code_at);
     JS_DECLARE_NATIVE_FUNCTION(repeat);
     JS_DECLARE_NATIVE_FUNCTION(starts_with);
     JS_DECLARE_NATIVE_FUNCTION(index_of);

+ 1 - 0
Libraries/LibJS/Tests/builtins/String/String.prototype-generic-functions.js

@@ -1,6 +1,7 @@
 test("basic functionality", () => {
     const genericStringPrototypeFunctions = [
         "charAt",
+        "charCodeAt",
         "repeat",
         "startsWith",
         "indexOf",

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

@@ -0,0 +1,21 @@
+test("basic functionality", () => {
+    expect(String.prototype.charAt).toHaveLength(1);
+
+    var s = "Foobar";
+    expect(typeof s).toBe("string");
+    expect(s).toHaveLength(6);
+
+    expect(s.charCodeAt(0)).toBe(70);
+    expect(s.charCodeAt(1)).toBe(111);
+    expect(s.charCodeAt(2)).toBe(111);
+    expect(s.charCodeAt(3)).toBe(98);
+    expect(s.charCodeAt(4)).toBe(97);
+    expect(s.charCodeAt(5)).toBe(114);
+    expect(s.charCodeAt(6)).toBe(NaN);
+    expect(s.charCodeAt(-1)).toBe(NaN);
+
+    expect(s.charCodeAt()).toBe(70);
+    expect(s.charCodeAt(NaN)).toBe(70);
+    expect(s.charCodeAt("foo")).toBe(70);
+    expect(s.charCodeAt(undefined)).toBe(70);
+});