From 315255942273d4488b94a06ce266cab92277f21f Mon Sep 17 00:00:00 2001 From: Linus Groh Date: Tue, 28 Apr 2020 18:10:40 +0100 Subject: LibJS: Call Array.prototype.findIndex() callback for empty elements If the array value at the current index is empty, the callback will be called with undefined as value. --- Libraries/LibJS/Runtime/ArrayPrototype.cpp | 12 ++++++------ Libraries/LibJS/Tests/Array.prototype.findIndex.js | 20 ++++++++++++++++++++ .../LibJS/Tests/array-shrink-during-find-crash.js | 2 +- 3 files changed, 27 insertions(+), 7 deletions(-) (limited to 'Libraries') diff --git a/Libraries/LibJS/Runtime/ArrayPrototype.cpp b/Libraries/LibJS/Runtime/ArrayPrototype.cpp index 9ee13271cc..5d30b07c20 100644 --- a/Libraries/LibJS/Runtime/ArrayPrototype.cpp +++ b/Libraries/LibJS/Runtime/ArrayPrototype.cpp @@ -489,12 +489,12 @@ Value ArrayPrototype::find_index(Interpreter& interpreter) auto array_size = array->elements().size(); for (size_t i = 0; i < array_size; ++i) { - if (i >= array->elements().size()) - break; - - auto value = array->elements().at(i); - if (value.is_empty()) - continue; + auto value = js_undefined(); + if (i < array->elements().size()) { + value = array->elements().at(i); + if (value.is_empty()) + value = js_undefined(); + } MarkedValueList arguments(interpreter.heap()); arguments.append(value); diff --git a/Libraries/LibJS/Tests/Array.prototype.findIndex.js b/Libraries/LibJS/Tests/Array.prototype.findIndex.js index 0795a66474..f5b2295930 100644 --- a/Libraries/LibJS/Tests/Array.prototype.findIndex.js +++ b/Libraries/LibJS/Tests/Array.prototype.findIndex.js @@ -23,6 +23,26 @@ try { assert(array.findIndex(value => value > 100) === -1); assert([].findIndex(value => value === 1) === -1); + var callbackCalled = 0; + var callback = () => { callbackCalled++; }; + + [].findIndex(callback) + assert(callbackCalled === 0); + + [1, 2, 3].findIndex(callback); + assert(callbackCalled === 3); + + callbackCalled = 0; + [1, , , "foo", , undefined, , ,].findIndex(callback); + assert(callbackCalled === 8); + + callbackCalled = 0; + [1, , , "foo", , undefined, , ,].findIndex(value => { + callbackCalled++; + return value === undefined; + }); + assert(callbackCalled === 2); + console.log("PASS"); } catch (e) { console.log("FAIL: " + e); diff --git a/Libraries/LibJS/Tests/array-shrink-during-find-crash.js b/Libraries/LibJS/Tests/array-shrink-during-find-crash.js index e2e65c39ea..16a041a8e7 100644 --- a/Libraries/LibJS/Tests/array-shrink-during-find-crash.js +++ b/Libraries/LibJS/Tests/array-shrink-during-find-crash.js @@ -17,7 +17,7 @@ try { callbackCalled++; a.pop(); }); - assert(callbackCalled === 3); + assert(callbackCalled === 5); console.log("PASS"); } catch (e) { -- cgit v1.2.3