LibJS: Add String.prototype.indexOf()

This commit is contained in:
Andreas Kling 2020-04-04 23:44:29 +02:00
parent 9e05672f87
commit 97cd1173fa
3 changed files with 36 additions and 0 deletions

View file

@ -33,6 +33,7 @@
#include <LibJS/Runtime/StringObject.h>
#include <LibJS/Runtime/StringPrototype.h>
#include <LibJS/Runtime/Value.h>
#include <string.h>
namespace JS {
@ -42,6 +43,7 @@ StringPrototype::StringPrototype()
put_native_function("charAt", char_at, 1);
put_native_function("repeat", repeat, 1);
put_native_function("startsWith", starts_with, 1);
put_native_function("indexOf", index_of, 1);
}
StringPrototype::~StringPrototype()
@ -110,6 +112,27 @@ Value StringPrototype::starts_with(Interpreter& interpreter)
return Value(underlying_string.substring(start, search_string_length) == search_string);
}
Value StringPrototype::index_of(Interpreter& interpreter)
{
auto* this_object = interpreter.this_value().to_object(interpreter.heap());
if (!this_object)
return {};
if (!this_object->is_string_object())
return interpreter.throw_exception<Error>("TypeError", "Not a String object");
Value needle_value = js_undefined();
if (interpreter.argument_count() >= 1)
needle_value = interpreter.argument(0);
auto needle = needle_value.to_string();
auto haystack = static_cast<const StringObject*>(this_object)->primitive_string()->string();
// FIXME: We should have a helper in AK::String for this.
auto* ptr = strstr(haystack.characters(), needle.characters());
if (!ptr)
return Value(-1);
return Value((i32)(ptr - haystack.characters()));
}
Value StringPrototype::length_getter(Interpreter& interpreter)
{
auto* this_object = interpreter.this_value().to_object(interpreter.heap());

View file

@ -41,6 +41,7 @@ private:
static Value char_at(Interpreter&);
static Value repeat(Interpreter&);
static Value starts_with(Interpreter&);
static Value index_of(Interpreter&);
static Value length_getter(Interpreter&);
};

View file

@ -0,0 +1,12 @@
function assert(x) { if (!x) throw 1; }
try {
var s = "hello friends"
assert(s.indexOf("friends") === 6);
assert(s.indexOf("enemies") === -1);
console.log("PASS");
} catch (e) {
console.log("FAIL: " + e);
}