2

When this method is called, it reverses the order of the items in the original array. Then then it returns that same, original array. No new arrays should need to be created to pass this kata. However, I'm trying to figure out how this.push(arr.pop()); works in this function.

Array.prototype.reverse = function() {
  var arr = this.splice(0);  //I understand first we remove all the items in the array starting from [0]

  while(arr.length) {    //then we run the arr.length of all the items? 
    this.push(arr.pop());  //then add the deleted last item? doesn't make sense...
  }   

  return this;
};

test cases:

Test.assertSimilar([1, 2, 3, 4].reverse(), [4,3,2,1]);
Test.assertSimilar(["a", "b", "c"].reverse(), ["c", "b", "a"]);
Test.assertSimilar([].reverse(), []);

or please write a function you think is a better solution

0

2 Answers 2

4

I've added comments:

Array.prototype.reverse = function() {
  var arr = this.splice(0);  // Removes all entries from `this` array AND returns
                             // them in a new array

  while(arr.length) {        // For as long as that new array still has items
                             // (length is "truthy" until it's 0)
    this.push(arr.pop());    // `pop` removes the LAST entry from `arr`, and
                             // `push` adds it to `this` as the next entry
  }   

  return this;
};

So say we have [1, 2, 3, 4, 5]:

  1. First those are removed from this and put in arr.
  2. Then, because arr.length is 5, we enter the body of the loop.
  3. arr.pop() removes 5 from arr.
  4. this.push() adds 5 to the next available location in this, which is at the beginning
  5. arr.length is now 4, so we go into the body again
  6. arr.pop() removes 4 from arr.
  7. this.push() adds 4 to the next available location in this, which is just after 5
  8. Rinse, repeat
  9. When arr.length is 0, it's not truthy anymore, and we exit the loop
Sign up to request clarification or add additional context in comments.

Comments

1

"or please write a function you think is a better solution"

Here's a more efficient and simpler solution:

Array.prototype.reverse = function() {
  for (var i = 0, j = this.length - 1; i < j; i++, j--) {
    var tmp = this[i];
    this[i] = this[j];
    this[j] = tmp;
  }
  return this;
};

In browsers that support ECMAScript 6, you can shorten it to this:

Array.prototype.reverse = function() {
  for (var i = 0, j = this.length - 1; i < j; i++, j--) {
    [this[i], this[j]] = [this[j], this[i]];
  }
  return this;
};

Not sure if there's any extra overhead.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.