You have two numeric variables
let a = 1;
let b = 2;
They need to be swapped, so that:
a === 2
b === 1
Simple Swap – No Restrictions
Since there are no restrictions, why not just introduce a third variable as temporary storage?
Easy peasy. Moving on.
Numeric Swap – Using only A and B
The variables serve as storage and you don’t have any storage, so one will need to contain both somehow with the ability to extract the original values.
What happens when you combine both values? You’re left with the combined value on the one hand and one part of the combined value on the other. Can that be served to determine both values in reverse?
Note: this solution is very likely to appear in code interviews. Want to make the interviewer feel a bit less confident? Ask to check this using a=0.1 and b=0.2 and prepare yourself for a good laugh on the interviewer’s expense…
String Swap – Using only A and B
Again we’ll need to store the combined value of both vars inside one of them and then extract the information somehow. This time we’ll need to employ some string related functions.
Any Swap – Swap Any Two Variables
You can’t assume anything, so combining the vars is out of the question. At least not directly…
Would it be possible to convert the var types without losing their original values?