From 731abd997833a4cd8524cd8c64e2817edb1182d4 Mon Sep 17 00:00:00 2001 From: Andreas Kling Date: Sun, 15 Mar 2020 21:17:18 +0100 Subject: [PATCH] LibJS: Add String.prototype.repeat() :^) --- Libraries/LibJS/StringPrototype.cpp | 21 ++++++++++++++++++--- 1 file changed, 18 insertions(+), 3 deletions(-) diff --git a/Libraries/LibJS/StringPrototype.cpp b/Libraries/LibJS/StringPrototype.cpp index 9be1eafdc1..d359cfdf4a 100644 --- a/Libraries/LibJS/StringPrototype.cpp +++ b/Libraries/LibJS/StringPrototype.cpp @@ -25,6 +25,7 @@ */ #include +#include #include #include #include @@ -34,13 +35,11 @@ namespace JS { - - StringPrototype::StringPrototype() { put_native_property( "length", [](Object* this_object) { - ASSERT(this_object); + ASSERT(this_object); ASSERT(this_object->is_string_object()); return Value((i32) static_cast(this_object)->primitive_string()->string().length()); }, @@ -56,6 +55,22 @@ StringPrototype::StringPrototype() return js_string(this_object->heap(), String::empty()); return js_string(this_object->heap(), underlying_string.substring(index, 1)); }); + put_native_function("repeat", [](Object* this_object, Vector arguments) -> Value { + ASSERT(this_object->is_string_object()); + if (arguments.is_empty()) + return js_string(this_object->heap(), String::empty()); + i32 count = 0; + count = arguments[0].to_i32(); + if (count < 0) { + // FIXME: throw RangeError + return js_undefined(); + } + auto* string_object = static_cast(this_object); + StringBuilder builder; + for (i32 i = 0; i < count; ++i) + builder.append(string_object->primitive_string()->string()); + return js_string(this_object->heap(), builder.to_string()); + }); } StringPrototype::~StringPrototype()