mirror of
https://github.com/RGBCube/serenity
synced 2025-07-27 16:07:46 +00:00
LibJS: Add Array.prototype.includes
This commit is contained in:
parent
a639172760
commit
687096cadd
3 changed files with 56 additions and 0 deletions
|
@ -56,6 +56,7 @@ ArrayPrototype::ArrayPrototype()
|
|||
put_native_function("indexOf", index_of, 1);
|
||||
put_native_function("reverse", reverse, 0);
|
||||
put_native_function("lastIndexOf", last_index_of, 1);
|
||||
put_native_function("includes", includes, 1);
|
||||
put("length", Value(0));
|
||||
}
|
||||
|
||||
|
@ -388,4 +389,38 @@ Value ArrayPrototype::last_index_of(Interpreter& interpreter)
|
|||
return Value(-1);
|
||||
}
|
||||
|
||||
Value ArrayPrototype::includes(Interpreter& interpreter)
|
||||
{
|
||||
auto* array = array_from(interpreter);
|
||||
if (!array)
|
||||
return {};
|
||||
|
||||
i32 array_size = static_cast<i32>(array->elements().size());
|
||||
if (interpreter.argument_count() == 0 || array_size == 0)
|
||||
return Value(false);
|
||||
|
||||
i32 from_index = 0;
|
||||
if (interpreter.argument_count() >= 2) {
|
||||
from_index = interpreter.argument(1).to_i32();
|
||||
|
||||
if (from_index >= array_size)
|
||||
return Value(false);
|
||||
|
||||
auto negative_min_index = ((array_size - 1) * -1);
|
||||
if (from_index < negative_min_index)
|
||||
from_index = 0;
|
||||
else if (from_index < 0)
|
||||
from_index = array_size + from_index;
|
||||
}
|
||||
|
||||
auto value_to_find = interpreter.argument(0);
|
||||
for (i32 i = from_index; i < array_size; ++i) {
|
||||
auto& element = array->elements().at(i);
|
||||
if (typed_eq(interpreter, element, value_to_find).as_bool())
|
||||
return Value(true);
|
||||
}
|
||||
|
||||
return Value(false);
|
||||
}
|
||||
|
||||
}
|
||||
|
|
|
@ -53,5 +53,6 @@ private:
|
|||
static Value index_of(Interpreter&);
|
||||
static Value reverse(Interpreter&);
|
||||
static Value last_index_of(Interpreter&);
|
||||
static Value includes(Interpreter&);
|
||||
};
|
||||
}
|
||||
|
|
Loading…
Add table
Add a link
Reference in a new issue