Skip to content

Commit

Permalink
Added array reverse (#695)
Browse files Browse the repository at this point in the history
  • Loading branch information
sh33dafi authored Jun 22, 2024
1 parent 12556f2 commit 552975d
Show file tree
Hide file tree
Showing 3 changed files with 31 additions and 0 deletions.
9 changes: 9 additions & 0 deletions devs/run-tests/24arraymap.ts
Original file line number Diff line number Diff line change
Expand Up @@ -220,6 +220,14 @@ function testArrayKeys() {
}
}

function testArrayReverse() {
const array = ['one', 'two', 'three'];

const reversed = array.reverse();
assert(reversed.join() === 'three,two,one', "reversed");
assert(array.join() === 'three,two,one', "reversedDestructive");
}

testArraySome()
testArrayEvery()
testArrayFill()
Expand All @@ -236,3 +244,4 @@ testArrayAt()
testArrayWith()
testArraySort()
testArrayKeys()
testArrayReverse()
16 changes: 16 additions & 0 deletions packages/core/src/array.ts
Original file line number Diff line number Diff line change
Expand Up @@ -215,6 +215,22 @@ Array.prototype.keys = function () {
return Array(this.length).fill(0).map((_, i) => i);
}

Array.prototype.reverse = function () {
const len = this.length;
const middle = Math.floor(len / 2);
let lower = 0;

while (lower !== middle) {
const upper = len - lower - 1;
const lowerValue = this[lower];
this[lower] = this[upper];
this[upper] = lowerValue;
lower++;
}
return this;
}


Buffer.prototype.set = function (other: Buffer, trgOff?: number) {
if (!trgOff) trgOff = 0
this.blitAt(trgOff, other, 0, other.length)
Expand Down
6 changes: 6 additions & 0 deletions packages/core/src/corelib.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -259,6 +259,12 @@ interface Array<T> {
*/
lastIndexOf(searchElement: T, fromIndex?: number): number

/**
* Reverses the elements in an array in place.
* This method mutates the array and returns a reference to the same array.
*/
reverse(): T[]

/**
* Returns a copy of a section of an array.
* For both start and end, a negative index can be used to indicate an offset from the end of the array.
Expand Down

0 comments on commit 552975d

Please sign in to comment.