diff options
author | davidot <david.tuin@gmail.com> | 2021-06-27 19:14:11 +0200 |
---|---|---|
committer | Linus Groh <mail@linusgroh.de> | 2021-06-30 16:08:00 +0100 |
commit | 36668893a6db429062aa925c809f88f5f2f3ea65 (patch) | |
tree | f05f1d8e5d0f9e1d2bebd7985130e104f71efb7f | |
parent | a4c1666b71e4b72fac860af4c31aa2ca8749b0e9 (diff) | |
download | serenity-36668893a6db429062aa925c809f88f5f2f3ea65.zip |
LibJS: Add String.prototype.indexOf position argument
-rw-r--r-- | Userland/Libraries/LibJS/Runtime/StringPrototype.cpp | 9 | ||||
-rw-r--r-- | Userland/Libraries/LibJS/Tests/builtins/String/String.prototype.indexOf.js | 15 |
2 files changed, 23 insertions, 1 deletions
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<double>(0), static_cast<double>(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); }); |