mirror of
https://github.com/RGBCube/serenity
synced 2025-07-26 23:17:46 +00:00
LibJS: Add Array.prototype.map()
This commit is contained in:
parent
f03d005bc4
commit
f7df521073
3 changed files with 78 additions and 0 deletions
|
@ -41,6 +41,7 @@ ArrayPrototype::ArrayPrototype()
|
|||
{
|
||||
put_native_function("filter", filter, 1);
|
||||
put_native_function("forEach", for_each, 1);
|
||||
put_native_function("map", map, 1);
|
||||
put_native_function("pop", pop, 0);
|
||||
put_native_function("push", push, 1);
|
||||
put_native_function("shift", shift, 0);
|
||||
|
@ -128,6 +129,31 @@ Value ArrayPrototype::for_each(Interpreter& interpreter)
|
|||
return js_undefined();
|
||||
}
|
||||
|
||||
Value ArrayPrototype::map(Interpreter& interpreter)
|
||||
{
|
||||
auto* array = array_from(interpreter);
|
||||
if (!array)
|
||||
return {};
|
||||
auto* callback = callback_from_args(interpreter, "map");
|
||||
if (!callback)
|
||||
return {};
|
||||
auto this_value = interpreter.argument(1);
|
||||
auto initial_array_size = array->elements().size();
|
||||
auto* new_array = interpreter.heap().allocate<Array>();
|
||||
for (size_t i = 0; i < initial_array_size; ++i) {
|
||||
if (i >= array->elements().size())
|
||||
break;
|
||||
auto value = array->elements()[i];
|
||||
if (value.is_empty())
|
||||
continue;
|
||||
auto result = interpreter.call(callback, this_value, { value, Value((i32)i), array });
|
||||
if (interpreter.exception())
|
||||
return {};
|
||||
new_array->elements().append(result);
|
||||
}
|
||||
return Value(new_array);
|
||||
}
|
||||
|
||||
Value ArrayPrototype::push(Interpreter& interpreter)
|
||||
{
|
||||
auto* array = array_from(interpreter);
|
||||
|
|
|
@ -41,6 +41,7 @@ private:
|
|||
|
||||
static Value filter(Interpreter&);
|
||||
static Value for_each(Interpreter&);
|
||||
static Value map(Interpreter&);
|
||||
static Value pop(Interpreter&);
|
||||
static Value push(Interpreter&);
|
||||
static Value shift(Interpreter&);
|
||||
|
|
Loading…
Add table
Add a link
Reference in a new issue