LibJS: Add String.prototype.toLowerCase()

This commit is contained in:
Andreas Kling 2020-04-06 20:46:08 +02:00
parent 220ecde626
commit cb18b2c74d
Notes: sideshowbarker 2024-07-19 07:50:39 +09:00
3 changed files with 33 additions and 0 deletions

View file

@ -44,6 +44,7 @@ StringPrototype::StringPrototype()
put_native_function("repeat", repeat, 1);
put_native_function("startsWith", starts_with, 1);
put_native_function("indexOf", index_of, 1);
put_native_function("toLowerCase", to_lowercase, 0);
}
StringPrototype::~StringPrototype()
@ -133,6 +134,26 @@ Value StringPrototype::index_of(Interpreter& interpreter)
return Value((i32)(ptr - haystack.characters()));
}
static StringObject* string_object_from(Interpreter& interpreter)
{
auto* this_object = interpreter.this_value().to_object(interpreter.heap());
if (!this_object)
return nullptr;
if (!this_object->is_string_object()) {
interpreter.throw_exception<Error>("TypeError", "Not a String object");
return nullptr;
}
return static_cast<StringObject*>(this_object);
}
Value StringPrototype::to_lowercase(Interpreter& interpreter)
{
auto* string_object = string_object_from(interpreter);
if (!string_object)
return {};
return js_string(interpreter, string_object->primitive_string()->string().to_lowercase());
}
Value StringPrototype::length_getter(Interpreter& interpreter)
{
auto* this_object = interpreter.this_value().to_object(interpreter.heap());

View file

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

View file

@ -0,0 +1,11 @@
try {
assert("foo".toLowerCase() === "foo");
assert("Foo".toLowerCase() === "foo");
assert("FOO".toLowerCase() === "foo");
assert(('b' + 'a' + + 'a' + 'a').toLowerCase() === "banana");
console.log("PASS");
} catch (e) {
console.log("FAIL: " + e);
}