1
Fork 0
mirror of https://github.com/RGBCube/serenity synced 2025-07-25 14:27:35 +00:00

LibJS: Implement String.prototype.startsWith()

This commit is contained in:
Linus Groh 2020-03-29 17:15:00 +01:00 committed by Andreas Kling
parent 7971af474d
commit 0a94661c14
3 changed files with 68 additions and 0 deletions

View file

@ -41,6 +41,7 @@ StringPrototype::StringPrototype()
put_native_property("length", length_getter, nullptr);
put_native_function("charAt", char_at);
put_native_function("repeat", repeat);
put_native_function("startsWith", starts_with);
}
StringPrototype::~StringPrototype()
@ -83,6 +84,32 @@ Value StringPrototype::repeat(Interpreter& interpreter)
return js_string(interpreter.heap(), builder.to_string());
}
Value StringPrototype::starts_with(Interpreter& interpreter)
{
auto* this_object = interpreter.this_value().to_object(interpreter.heap());
if (!this_object)
return {};
if (interpreter.call_frame().arguments.is_empty())
return Value(false);
auto search_string = interpreter.call_frame().arguments[0].to_string();
auto search_string_length = static_cast<i32>(search_string.length());
i32 position = 0;
if (interpreter.call_frame().arguments.size() > 1) {
auto number = interpreter.call_frame().arguments[1].to_number();
if (!number.is_nan())
position = number.to_i32();
}
ASSERT(this_object->is_string_object());
auto underlying_string = static_cast<const StringObject*>(this_object)->primitive_string()->string();
auto underlying_string_length = static_cast<i32>(underlying_string.length());
auto start = min(max(position, 0), underlying_string_length);
if (start + search_string_length > underlying_string_length)
return Value(false);
if (search_string_length == 0)
return Value(true);
return Value(underlying_string.substring(start, search_string_length) == search_string);
}
Value StringPrototype::length_getter(Interpreter& interpreter)
{
auto* this_object = interpreter.this_value().to_object(interpreter.heap());

View file

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