Skip to content

Commit

Permalink
LibJS: Add String.prototype.indexOf position argument
Browse files Browse the repository at this point in the history
  • Loading branch information
davidot authored and linusg committed Jun 30, 2021
1 parent a4c1666 commit 3666889
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 1 deletion.
9 changes: 8 additions & 1 deletion Userland/Libraries/LibJS/Runtime/StringPrototype.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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);
});

0 comments on commit 3666889

Please sign in to comment.