1
Fork 0
mirror of https://github.com/RGBCube/serenity synced 2025-07-26 11:37:44 +00:00

LibJS: Add Array.prototype.findIndex

This commit is contained in:
Kesse Jones 2020-04-26 13:22:09 -03:00 committed by Andreas Kling
parent bf9926743a
commit 36c00e8078
3 changed files with 65 additions and 0 deletions

View file

@ -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);
}
}

View file

@ -55,5 +55,6 @@ private:
static Value last_index_of(Interpreter&);
static Value includes(Interpreter&);
static Value find(Interpreter&);
static Value find_index(Interpreter&);
};
}