From 36668893a6db429062aa925c809f88f5f2f3ea65 Mon Sep 17 00:00:00 2001 From: davidot Date: Sun, 27 Jun 2021 19:14:11 +0200 Subject: LibJS: Add String.prototype.indexOf position argument --- Userland/Libraries/LibJS/Runtime/StringPrototype.cpp | 9 ++++++++- .../Tests/builtins/String/String.prototype.indexOf.js | 15 +++++++++++++++ 2 files changed, 23 insertions(+), 1 deletion(-) diff --git a/Userland/Libraries/LibJS/Runtime/StringPrototype.cpp b/Userland/Libraries/LibJS/Runtime/StringPrototype.cpp index ff2f6d673e..c7a2c3c5ec 100644 --- a/Userland/Libraries/LibJS/Runtime/StringPrototype.cpp +++ b/Userland/Libraries/LibJS/Runtime/StringPrototype.cpp @@ -284,7 +284,14 @@ JS_DEFINE_NATIVE_FUNCTION(StringPrototype::index_of) auto needle = vm.argument(0).to_string(global_object); if (vm.exception()) return {}; - return Value((i32)string->find(needle).value_or(-1)); + size_t from = 0; + if (vm.argument_count() > 1) { + double from_argument = vm.argument(1).to_integer_or_infinity(global_object); + if (vm.exception()) + return {}; + from = clamp(from_argument, static_cast(0), static_cast(string->length())); + } + return Value((i32)string->find(needle, from).value_or(-1)); } // 22.1.3.26 String.prototype.toLowerCase ( ), https://tc39.es/ecma262/#sec-string.prototype.tolowercase diff --git a/Userland/Libraries/LibJS/Tests/builtins/String/String.prototype.indexOf.js b/Userland/Libraries/LibJS/Tests/builtins/String/String.prototype.indexOf.js index 8e2ca2f892..ff557ccc53 100644 --- a/Userland/Libraries/LibJS/Tests/builtins/String/String.prototype.indexOf.js +++ b/Userland/Libraries/LibJS/Tests/builtins/String/String.prototype.indexOf.js @@ -5,4 +5,19 @@ test("basic functionality", () => { expect(s.indexOf("friends")).toBe(6); expect(s.indexOf("enemies")).toBe(-1); + + expect(s.indexOf("friends", 0)).toBe(6); + expect(s.indexOf("enemies", 0)).toBe(-1); + + expect(s.indexOf("friends", 4)).toBe(6); + expect(s.indexOf("friends", 6)).toBe(6); + expect(s.indexOf("friends", 7)).toBe(-1); + expect(s.indexOf("friends", 8)).toBe(-1); + + expect(s.indexOf("enemies", 2)).toBe(-1); + expect(s.indexOf("enemies", 7)).toBe(-1); + + expect(s.indexOf("e")).toBe(1); + expect(s.indexOf("e", 0)).toBe(1); + expect(s.indexOf("e", 2)).toBe(9); }); -- cgit v1.2.3