Search code examples
javascriptswap

Is it possible to write a numeric swap() function in JavaScript?


A swap() function would result in cleaner code (DRY) than doing the work inline. Unfortunately, the following function accomplished nothing because in JavaScript parameters are always pass-by-value:

function swap(a,b) { var temp=a; a=b; b=temp; }

Is there any way of writing a function that accomplished what this is attempting, particularly for numeric values?

I'm not impressed with the answers to this related question.
This answer has the right idea, but doesn't handle the general case.


Solution

  • I found this approach, which isn't too bad (at least for my purposes):

    function swap( swap_name_a, swap_name_b )
       {
       eval
          (
          "var swap_temp="+swap_name_a+";"
        + swap_name_a+"="+swap_name_b+";"
        + swap_name_b+"=swap_temp;"
          );
       }
    

    You are required to quote the arguments:

    swap('a','b');
    

    It seems to also work with more complex arguments:

    swap('list[index1]','list[index2]');
    

    Note: You will need to implement the swap() function within each scope that it will be used because it must have access to the named arguments. This goes against the "don't-repeat-yourself" principal, but in some circumstances it may be acceptable to copy-and-paste a bit of boilerplate code like this if it results in simplification of your algorithm logic.


    By the way: The example from which I derived this returned the string from swap() and relied on the caller to forward the string to eval: eval(swap('a','b')). This solves the scope problem, but makes the swap operation more error prone -- and less attractive.

    Be careful, that source also warned that this method could result in taunting.


    Will time-traveling space-vampires steal your credit cards if you use eval()? You should decide that for yourself, but here's some help:

    The biggest concern I see is that this might be relatively slow (depending on how the interpreter manages caching). If it is too slow for your purposes, then don't use it.