mirror of
https://github.com/RGBCube/serenity
synced 2025-07-27 11:57:35 +00:00
LibJS: Optimize & Bring String.prototype.repeat closer to the spec
Specifically, we immediately return an empty string when `this` is an empty string, instead of wasting time in a loop doing nothing N times.
This commit is contained in:
parent
5f09d78b9d
commit
7d055dd039
1 changed files with 15 additions and 6 deletions
|
@ -167,21 +167,30 @@ JS_DEFINE_NATIVE_FUNCTION(StringPrototype::repeat)
|
||||||
auto string = ak_string_from(vm, global_object);
|
auto string = ak_string_from(vm, global_object);
|
||||||
if (!string.has_value())
|
if (!string.has_value())
|
||||||
return {};
|
return {};
|
||||||
if (!vm.argument_count())
|
|
||||||
return js_string(vm, String::empty());
|
auto n = vm.argument(0).to_integer_or_infinity(global_object);
|
||||||
auto count = vm.argument(0).to_integer_or_infinity(global_object);
|
|
||||||
if (vm.exception())
|
if (vm.exception())
|
||||||
return {};
|
return {};
|
||||||
if (count < 0) {
|
|
||||||
|
if (n < 0) {
|
||||||
vm.throw_exception<RangeError>(global_object, ErrorType::StringRepeatCountMustBe, "positive");
|
vm.throw_exception<RangeError>(global_object, ErrorType::StringRepeatCountMustBe, "positive");
|
||||||
return {};
|
return {};
|
||||||
}
|
}
|
||||||
if (Value(count).is_infinity()) {
|
|
||||||
|
if (Value(n).is_positive_infinity()) {
|
||||||
vm.throw_exception<RangeError>(global_object, ErrorType::StringRepeatCountMustBe, "finite");
|
vm.throw_exception<RangeError>(global_object, ErrorType::StringRepeatCountMustBe, "finite");
|
||||||
return {};
|
return {};
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if (n == 0)
|
||||||
|
return js_string(vm, String::empty());
|
||||||
|
|
||||||
|
// NOTE: This is an optimization, it is not required by the specification but it produces equivalent behaviour
|
||||||
|
if (string->is_empty())
|
||||||
|
return js_string(vm, String::empty());
|
||||||
|
|
||||||
StringBuilder builder;
|
StringBuilder builder;
|
||||||
for (size_t i = 0; i < count; ++i)
|
for (size_t i = 0; i < n; ++i)
|
||||||
builder.append(*string);
|
builder.append(*string);
|
||||||
return js_string(vm, builder.to_string());
|
return js_string(vm, builder.to_string());
|
||||||
}
|
}
|
||||||
|
|
Loading…
Add table
Add a link
Reference in a new issue