summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorSimon Rask <simon.ras.and@gmail.com>2022-10-13 19:07:44 +0200
committerLinus Groh <mail@linusgroh.de>2022-10-13 21:14:32 +0200
commit8701832095edc1eca17ca776954efe35b5e0ce7c (patch)
tree13f05596f3557130b78b4a8c1e07acaded4b5976
parent1d058ffd723a6c0b245bf12a4eb05bf6c4d10ed9 (diff)
downloadserenity-8701832095edc1eca17ca776954efe35b5e0ce7c.zip
LibJS: Add spec comments to String.prototype.substring
-rw-r--r--Userland/Libraries/LibJS/Runtime/StringPrototype.cpp11
1 files changed, 11 insertions, 0 deletions
diff --git a/Userland/Libraries/LibJS/Runtime/StringPrototype.cpp b/Userland/Libraries/LibJS/Runtime/StringPrototype.cpp
index 2762195775..d43e41429f 100644
--- a/Userland/Libraries/LibJS/Runtime/StringPrototype.cpp
+++ b/Userland/Libraries/LibJS/Runtime/StringPrototype.cpp
@@ -549,20 +549,31 @@ JS_DEFINE_NATIVE_FUNCTION(StringPrototype::concat)
// 22.1.3.24 String.prototype.substring ( start, end ), https://tc39.es/ecma262/#sec-string.prototype.substring
JS_DEFINE_NATIVE_FUNCTION(StringPrototype::substring)
{
+ // 1. Let O be ? RequireObjectCoercible(this value).
+ // 2. Let S be ? ToString(O).
auto string = TRY(utf16_string_from(vm));
+
+ // 3. Let len be the length of S.
auto string_length = static_cast<double>(string.length_in_code_units());
+ // 4. Let intStart be ? ToIntegerOrInfinity(start).
auto start = TRY(vm.argument(0).to_integer_or_infinity(vm));
+ // 5. If end is undefined, let intEnd be len; else let intEnd be ? ToIntegerOrInfinity(end).
auto end = string_length;
if (!vm.argument(1).is_undefined())
end = TRY(vm.argument(1).to_integer_or_infinity(vm));
+ // 6. Let finalStart be the result of clamping intStart between 0 and len.
size_t final_start = clamp(start, static_cast<double>(0), string_length);
+ // 7. Let finalEnd be the result of clamping intEnd between 0 and len.
size_t final_end = clamp(end, static_cast<double>(0), string_length);
+ // 8. Let from be min(finalStart, finalEnd).
size_t from = min(final_start, final_end);
+ // 9. Let to be max(finalStart, finalEnd).
size_t to = max(final_start, final_end);
+ // 10. Return the substring of S from from to to.
return js_string(vm, string.substring_view(from, to - from));
}