diff options
author | Linus Groh <mail@linusgroh.de> | 2020-05-22 18:21:33 +0100 |
---|---|---|
committer | Andreas Kling <kling@serenityos.org> | 2020-05-23 00:02:13 +0200 |
commit | 843e000f1870033d5043cd58b77d8358f5da9cb6 (patch) | |
tree | 57c145af4dfdd66dc5cb37d1196eeeaf75757a2b /Libraries/LibJS | |
parent | 6a4280e6e52533a9fc242826dacd91c1c43142c8 (diff) | |
download | serenity-843e000f1870033d5043cd58b77d8358f5da9cb6.zip |
LibJS: Fix Array.prototype.lastIndexOf() implementation
Diffstat (limited to 'Libraries/LibJS')
-rw-r--r-- | Libraries/LibJS/Runtime/ArrayPrototype.cpp | 13 | ||||
-rw-r--r-- | Libraries/LibJS/Tests/Array.prototype.lastIndexOf.js | 5 |
2 files changed, 8 insertions, 10 deletions
diff --git a/Libraries/LibJS/Runtime/ArrayPrototype.cpp b/Libraries/LibJS/Runtime/ArrayPrototype.cpp index edfa930ed2..983e4c36b6 100644 --- a/Libraries/LibJS/Runtime/ArrayPrototype.cpp +++ b/Libraries/LibJS/Runtime/ArrayPrototype.cpp @@ -414,22 +414,19 @@ Value ArrayPrototype::last_index_of(Interpreter& interpreter) if (array_size == 0) return Value(-1); - i32 from_index = 0; + i32 from_index = array_size - 1; if (interpreter.argument_count() >= 2) { from_index = interpreter.argument(1).to_i32(interpreter); if (interpreter.exception()) return {}; - if (from_index >= array_size) - return Value(-1); - auto negative_min_index = ((array_size - 1) * -1); - if (from_index < negative_min_index) - from_index = 0; - else if (from_index < 0) + if (from_index >= 0) + from_index = min(from_index, array_size - 1); + else from_index = array_size + from_index; } auto search_element = interpreter.argument(0); - for (i32 i = array_size - 1; i >= from_index; --i) { + for (i32 i = from_index; i >= 0; --i) { auto& element = array->elements().at(i); if (strict_eq(interpreter, element, search_element)) return Value(i); diff --git a/Libraries/LibJS/Tests/Array.prototype.lastIndexOf.js b/Libraries/LibJS/Tests/Array.prototype.lastIndexOf.js index 1ae10c4e55..c2b1df8d4b 100644 --- a/Libraries/LibJS/Tests/Array.prototype.lastIndexOf.js +++ b/Libraries/LibJS/Tests/Array.prototype.lastIndexOf.js @@ -6,11 +6,12 @@ try { var array = [1, 2, 3, 1, "hello"]; assert(array.lastIndexOf("hello") === 4); + assert(array.lastIndexOf("hello", 1000) === 4); assert(array.lastIndexOf(1) === 3); - assert(array.lastIndexOf(1, -1) === -1); + assert(array.lastIndexOf(1, -1) === 3); assert(array.lastIndexOf(1, -2) === 3); assert(array.lastIndexOf(2) === 1); - assert(array.lastIndexOf(2, -3) === -1); + assert(array.lastIndexOf(2, -3) === 1); assert(array.lastIndexOf(2, -4) === 1); assert([].lastIndexOf('hello') === -1); assert([].lastIndexOf('hello', 10) === -1); |