Pārlūkot izejas kodu

LibJS: Add String.prototype.includes

Kesse Jones 5 gadi atpakaļ
vecāks
revīzija
838127df35

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

@@ -57,6 +57,7 @@ StringPrototype::StringPrototype()
     put_native_function("trimEnd", trim_end, 0);
     put_native_function("trimEnd", trim_end, 0);
     put_native_function("concat", concat, 1);
     put_native_function("concat", concat, 1);
     put_native_function("substring", substring, 2);
     put_native_function("substring", substring, 2);
+    put_native_function("includes", includes, 1);
 }
 }
 
 
 StringPrototype::~StringPrototype()
 StringPrototype::~StringPrototype()
@@ -368,4 +369,32 @@ Value StringPrototype::substring(Interpreter& interpreter)
     return js_string(interpreter, string_part);
     return js_string(interpreter, string_part);
 }
 }
 
 
+Value StringPrototype::includes(Interpreter& interpreter)
+{
+    auto* this_object = interpreter.this_value().to_object(interpreter.heap());
+    if (!this_object)
+        return {};
+
+    auto& string = this_object->to_string().as_string()->string();
+    auto search_string = interpreter.argument(0).to_string();
+    i32 position = 0;
+
+    if (interpreter.argument_count() >= 2) {
+        position = interpreter.argument(1).to_i32();
+
+        if (position >= static_cast<i32>(string.length()))
+            return Value(false);
+
+        if (position < 0)
+            position = 0;
+    }
+
+    if (position == 0)
+        return Value(string.contains(search_string));
+
+    auto substring_length = string.length() - position;
+    auto substring_search = string.substring(position, substring_length);
+    return Value(substring_search.contains(search_string));
+}
+
 }
 }

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

@@ -55,6 +55,7 @@ private:
     static Value trim_start(Interpreter&);
     static Value trim_start(Interpreter&);
     static Value trim_end(Interpreter&);
     static Value trim_end(Interpreter&);
     static Value concat(Interpreter&);
     static Value concat(Interpreter&);
+    static Value includes(Interpreter&);
 };
 };
 
 
 }
 }

+ 18 - 0
Libraries/LibJS/Tests/String.prototype.includes.js

@@ -0,0 +1,18 @@
+load("test-common.js");
+
+try {
+    assert(String.prototype.includes.length === 1);
+
+    assert("hello friends".includes("hello") === true);
+    assert("hello friends".includes("hello", 100) === false);
+    assert("hello friends".includes("hello", -10) === true);
+    assert("hello friends".includes("friends", 6) === true);
+    assert("hello friends".includes("hello", 6) === false);
+    assert("hello friends false".includes(false) === true);
+    assert("hello 10 friends".includes(10) === true);
+    assert("hello friends undefined".includes() === true);
+
+    console.log("PASS");
+} catch (err) {
+    console.log("FAIL: " + err);
+}