diff options
author | Kesse Jones <kjonesfc@outlook.com> | 2020-04-26 13:22:09 -0300 |
---|---|---|
committer | Andreas Kling <kling@serenityos.org> | 2020-04-27 11:23:23 +0200 |
commit | 36c00e8078c011a9b0e75a4f547c71a195d8e724 (patch) | |
tree | 90ec741ffe4d69b3d7b97fe4b52c45f733951469 /Libraries/LibJS/Runtime | |
parent | bf9926743a97264d81ff0be76a97e3e10cfc5988 (diff) | |
download | serenity-36c00e8078c011a9b0e75a4f547c71a195d8e724.zip |
LibJS: Add Array.prototype.findIndex
Diffstat (limited to 'Libraries/LibJS/Runtime')
-rw-r--r-- | Libraries/LibJS/Runtime/ArrayPrototype.cpp | 35 | ||||
-rw-r--r-- | Libraries/LibJS/Runtime/ArrayPrototype.h | 1 |
2 files changed, 36 insertions, 0 deletions
diff --git a/Libraries/LibJS/Runtime/ArrayPrototype.cpp b/Libraries/LibJS/Runtime/ArrayPrototype.cpp index 674d500fa3..f208973621 100644 --- a/Libraries/LibJS/Runtime/ArrayPrototype.cpp +++ b/Libraries/LibJS/Runtime/ArrayPrototype.cpp @@ -58,6 +58,7 @@ ArrayPrototype::ArrayPrototype() put_native_function("lastIndexOf", last_index_of, 1); put_native_function("includes", includes, 1); put_native_function("find", find, 1); + put_native_function("findIndex", find_index, 1); put("length", Value(0)); } @@ -458,4 +459,38 @@ Value ArrayPrototype::find(Interpreter& interpreter) return js_undefined(); } +Value ArrayPrototype::find_index(Interpreter& interpreter) +{ + auto* array = array_from(interpreter); + if (!array) + return {}; + + auto* callback = callback_from_args(interpreter, "findIndex"); + if (!callback) + return {}; + + auto this_value = interpreter.argument(1); + auto array_size = array->elements().size(); + + for (size_t i = 0; i < array_size; ++i) { + auto value = array->elements().at(i); + if (value.is_empty()) + continue; + + MarkedValueList arguments(interpreter.heap()); + arguments.append(value); + arguments.append(Value((i32)i)); + arguments.append(array); + + auto result = interpreter.call(callback, this_value, move(arguments)); + if (interpreter.exception()) + return {}; + + if (result.to_boolean()) + return Value((i32)i); + } + + return Value(-1); +} + } diff --git a/Libraries/LibJS/Runtime/ArrayPrototype.h b/Libraries/LibJS/Runtime/ArrayPrototype.h index b5912ee96f..30f4c6f000 100644 --- a/Libraries/LibJS/Runtime/ArrayPrototype.h +++ b/Libraries/LibJS/Runtime/ArrayPrototype.h @@ -55,5 +55,6 @@ private: static Value last_index_of(Interpreter&); static Value includes(Interpreter&); static Value find(Interpreter&); + static Value find_index(Interpreter&); }; } |