Recently, I've decided to get into the nitty gritty of JS benchmarking, and decided that to defeat the native reverse function, I should understand what it does under the hood.
I've been reading through the ECMAscript docs for array.prototype.reverse, and although the syntax used is somewhat mystifying, I've gathered the method performs a half loop and sets the upper bound to length -1 -i, which is the way I would do it. Inside the loop, I think the actual value swap is handled by the following code:
If lowerExists is true and upperExists is true, then
Perform ? Set(O, lowerP, upperValue, true).
Perform ? Set(O, upperP, lowerValue, true).
The Set ( O, P, V, Throw ) method appears to be an action verb, in that it actually sets a value. Let's take a closer look.
The abstract operation Set takes arguments O (an Object), P (a property key), V (an ECMAScript language value), and Throw (a Boolean). It is used to set the value of a specific property of an object. V is the new value for the property. It performs the following steps when called:
Assert: Type(O) is Object.
Assert: IsPropertyKey(P) is true.
Assert: Type(Throw) is Boolean.
Let success be ? O.[[Set]](P, V, O).
If success is false and Throw is true, throw a TypeError exception.
Return success.
A problem arises when we get to line 4: the function is defined in terms of itself.
My questions are:
- What does array.prototype.reverse do under the hood, and am I looking in the right place for that?
- Is Set ( O, P, V, Throw ) equivalent to map.set(k,v)?
- What efficiencies are gained by using the Set ( O, P, V, Throw ) method? Is this literally the method used, or is this just an abstract representation of some magic performed by the engine?
- Can the entire reverse() function be (faithfully) recreated in regular javascript code, and what would that look like? I'm already familiar with the usual examples on Stackoverflow.