15.4.4.8 Array.prototype.reverse()

2010-07-05

array Array.prototype.reverse()

Reverses the order of this array IN PLACE. So no new array is created and this array (coerced to an object) is returned after reversing!

Code: (Meta Ecma)
Array.prototype.reverse = function(){
var O = ToObject(this);
var lenVal = O.[[Get]]("length");
var len = ToUint32(lenVal);
var middle = Math.floor(len/2);
var lower = 0;
while (lower != middle) {
var upper = len - lower - 1;
var upperP = ToString(upper);
var lowerP = ToString(lower);
var lowerValue = O.[[Get]](lowerP);
var upperValue = O.[[Get]](upperP);
var lowerExists = O.[[HasProperty]](lowerP);
var upperExists = O.[[HasProperty]](upperP);
if (lowerExists && upperExists) {
O.[[Put]](lowerP, upperValue, true);
O.[[Put]](upperP, lowerValue, true);
} else if (upperExists) { // if only lowerExists = false
O.[[Put]](lowerP, upperValue, true);
O.[[Delete]](upperP, true);
} else if (lowerExists) { // if only upperExists is false
O.[[Delete]](lowerP, true);
O.[[Put]](upperP, lowerValue, true);
} // else nothing needs to be done
}
++lower;
}

Again, this function changes and returns the value of this array, rather then creating a new array with the result.