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

LibJS: Add Array.prototype.find

This commit is contained in:
Kesse Jones 2020-04-23 20:00:27 -03:00 committed by Andreas Kling
parent fd5f05079d
commit b0ca174d49
3 changed files with 65 additions and 0 deletions

View file

@ -57,6 +57,7 @@ ArrayPrototype::ArrayPrototype()
put_native_function("reverse", reverse, 0);
put_native_function("lastIndexOf", last_index_of, 1);
put_native_function("includes", includes, 1);
put_native_function("find", find, 1);
put("length", Value(0));
}
@ -423,4 +424,38 @@ Value ArrayPrototype::includes(Interpreter& interpreter)
return Value(false);
}
Value ArrayPrototype::find(Interpreter& interpreter)
{
auto* array = array_from(interpreter);
if (!array)
return {};
auto* callback = callback_from_args(interpreter, "find");
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;
}
return js_undefined();
}
}

View file

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