mirror of
https://github.com/RGBCube/serenity
synced 2025-07-26 00:27:43 +00:00
LibJS: Add Array.prototype.reverse
This commit is contained in:
parent
e35219b5ce
commit
df6696f576
3 changed files with 54 additions and 0 deletions
|
@ -54,6 +54,7 @@ ArrayPrototype::ArrayPrototype()
|
|||
put_native_function("concat", concat, 1);
|
||||
put_native_function("slice", slice, 2);
|
||||
put_native_function("indexOf", index_of, 1);
|
||||
put_native_function("reverse", reverse, 0);
|
||||
put("length", Value(0));
|
||||
}
|
||||
|
||||
|
@ -343,4 +344,25 @@ Value ArrayPrototype::index_of(Interpreter& interpreter)
|
|||
|
||||
return Value(-1);
|
||||
}
|
||||
|
||||
Value ArrayPrototype::reverse(Interpreter& interpreter)
|
||||
{
|
||||
auto* array = array_from(interpreter);
|
||||
if (!array)
|
||||
return {};
|
||||
|
||||
if (array->elements().size() == 0)
|
||||
return array;
|
||||
|
||||
Vector<Value> array_reverse;
|
||||
array_reverse.ensure_capacity(array->elements().size());
|
||||
|
||||
for (ssize_t i = array->elements().size() - 1; i >= 0; --i)
|
||||
array_reverse.append(array->elements().at(i));
|
||||
|
||||
array->elements() = move(array_reverse);
|
||||
|
||||
return array;
|
||||
}
|
||||
|
||||
}
|
||||
|
|
|
@ -51,5 +51,6 @@ private:
|
|||
static Value concat(Interpreter&);
|
||||
static Value slice(Interpreter&);
|
||||
static Value index_of(Interpreter&);
|
||||
static Value reverse(Interpreter&);
|
||||
};
|
||||
}
|
||||
|
|
31
Libraries/LibJS/Tests/Array.prototype.reverse.js
Normal file
31
Libraries/LibJS/Tests/Array.prototype.reverse.js
Normal file
|
@ -0,0 +1,31 @@
|
|||
load("test-common.js");
|
||||
|
||||
try {
|
||||
assert(Array.prototype.reverse.length === 0);
|
||||
|
||||
var array = [1, 2, 3];
|
||||
|
||||
assert(array[0] === 1);
|
||||
assert(array[1] === 2);
|
||||
assert(array[2] === 3);
|
||||
|
||||
array.reverse();
|
||||
|
||||
assert(array[0] === 3);
|
||||
assert(array[1] === 2);
|
||||
assert(array[2] === 1);
|
||||
|
||||
var array_ref = array.reverse();
|
||||
|
||||
assert(array_ref[0] === 1);
|
||||
assert(array_ref[1] === 2);
|
||||
assert(array_ref[2] === 3);
|
||||
|
||||
assert(array[0] === 1);
|
||||
assert(array[1] === 2);
|
||||
assert(array[2] === 3);
|
||||
|
||||
console.log("PASS");
|
||||
} catch (e) {
|
||||
console.log("FAIL: " + e);
|
||||
}
|
Loading…
Add table
Add a link
Reference in a new issue