Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Swapping Two Numbers, but only in a special case

I guess we all know about destructuring to swap two variables a and b, namely: [a, b] = [b, a] and other clever ways like a = b + (b = a, 0). However, I have a different situation which I feel should have a simple answer.

I have a variable a that can be one of 0, 1, 2, 3, 4, 5, or 6. If it is a===3 then I want a to reassign to 4. If a===4 then I want a to reassign to 3. BUT if a is any of the other values, I want it to remain the same.

So is there a clever, 1 line bit of code that can do this? For completeness, I want a short version of this:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

switch(a){
    case 3: a = 4; break;
    case 4: a = 3; break;
    // default: a = a; break; // Hashed out, because it is not needed
}

>Solution :

Using a Computed Property Name

function test(a) {
  a = { [a]: a, 3: 4, 4: 3 }[a]; 
  return a;
}


[0, 1, 2, 3, 4, 5].forEach(n =>console.log(n, test(n)));
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading