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:
switch(a){
case 3: a = 4; break;
case 4: a = 3; break;
// default: a = a; break; // Hashed out, because it is not needed
}
You could take an object for swapping the values and the value directly as default value, like
a = { 3: 4, 4: 3 }[a] || a;
If you like to work with a falsy value, like zero, you could take the Nullish coalescing operator ?? instead of logical OR ||.
a = { 3: 4, 4: 3 }[a] ?? a;
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)));
You could use nested ternary operators, but I think your current switch code is easier to understand:
a = a === 3 ? 4 : a === 4 ? 3 : a;