0

I need to write a swapping function. Assume an example input of [1,2]. This is what I have right now:

function swapValues() {
    var args = Array.prototype.slice.call(arguments);
    console.log(args[0]);

    var temp = args[0];
    args[0] = args[1];
    args[1] = temp;

    return args;
}

I'm not getting the desired swap functionality, so I put the console.log statement in to see what is happening. The problem is I'm getting [1 , 2] printed to the console, but I'm only expecting one. The values returned are not swapped.

user137717
  • 2,005
  • 4
  • 25
  • 48
  • You should read this: http://stackoverflow.com/questions/7056925/how-does-array-prototype-slice-call-work – Kyle Emmanuel Dec 17 '14 at 05:19
  • it works for me : `swap(1,2)` yields `[2,1]` – Valentin Waeselynck Dec 17 '14 at 05:19
  • Should you input be `[1, 2]` or simply `1, 2`? my guess would be @ValentinWaeselynck has it right. – rfornal Dec 17 '14 at 05:25
  • the input is an array. I modified the function to take an array as a parameter and then operated on / returned that array. It passed the test suite, but i can see how it could be made more general by just taking in anything the user provides and using ....slice.call to convert it to an array and swap those values – user137717 Dec 17 '14 at 05:31
  • @KyleEmmanuel thanks, I actually just read that before posting this. I think the test suite I was provided with just didn't provide clear instructions for this function. – user137717 Dec 17 '14 at 05:34
  • you can simply use apply() on it (as written) to process arrays – dandavis Dec 17 '14 at 05:43

1 Answers1

2

Why not use Array.protoype.reverse? I would do this:

function swapValues() {
    var args = Array.prototype.slice.call(arguments);
    return args.reverse();
}
garbanzio
  • 846
  • 1
  • 7
  • 10