diff options
author | Andreas Kling <kling@serenityos.org> | 2020-03-15 21:17:18 +0100 |
---|---|---|
committer | Andreas Kling <kling@serenityos.org> | 2020-03-15 21:17:38 +0100 |
commit | 731abd997833a4cd8524cd8c64e2817edb1182d4 (patch) | |
tree | e76858507ebd2bdbb30bd4a030650a3951d0d126 | |
parent | 63b3cfdc7361ea11b253c07f10e74987f8019f23 (diff) | |
download | serenity-731abd997833a4cd8524cd8c64e2817edb1182d4.zip |
LibJS: Add String.prototype.repeat() :^)
-rw-r--r-- | Libraries/LibJS/StringPrototype.cpp | 21 |
1 files 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 <AK/Function.h> +#include <AK/StringBuilder.h> #include <LibJS/Heap.h> #include <LibJS/Interpreter.h> #include <LibJS/PrimitiveString.h> @@ -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<const StringObject*>(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<Value> 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<StringObject*>(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() |