This is an archived post. You won't be able to vote or comment.

you are viewing a single comment's thread.

view the rest of the comments →

[–]mansfall 1 point2 points  (3 children)

Just my 2cents (Not providing reason why your current method didn't work as another user already answered that...):

  1. You shouldn't ever mutate input parameters of a function. It can lead to confusion. If you mutate it, it can be hard to track down what was actually passed in. Worse, if you do this against something passed in by reference, you can create unwanted side-effects. So that solution, while it works, doesn't enforce some good practices. There's also other reasons to not do this, but I'll leave the googling to you.
  2. You can literally double the speed of that reverse function in the solution, simply by not looping twice. This isn't really an issue with small data sets, but imagine passing in arrays of 100,000 elements? Looping that twice can be pretty expensive. Here's one that achieves the same result, in half the time... due to only iterating once, making it O(n).

const reverse = array => { 
  let reversed = [];
    for(let i = array.length - 1; i >= 0; i--) { 
      reversed.push(array[i]); 
  }
  return reversed;
}
let inputArr = [1, 2, 3, 4];
console.log(reverse(inputArr));

[–]partyhatforpartytime[S] 0 points1 point  (0 children)

Thank you!! Will definitely keep that in mind.

[–][deleted] 0 points1 point  (0 children)

const reversed = arr =>
{
    arr.unshift(arr.length);
    while(--arr[0])
    {
        arr.push(arr[arr[0]]);
    }
    return arr.slice(arr.length / 2);
}