Javascript Nonsense
Saw this online and then thought about it more and it cuts to the representation of numbers in bytes in binary quite clearly.
Given that you have two numeric variables how do you swap the values?
let firstNumber = 1;
let secondNumber = 2;
Output
> let firstNumber = 1
> let secondNumber = 2
> firstNumber
1
> secondNumber
2
Introduce a variable
let tempNumber = firstNumber;
firstNumber = secondNumber;
secondNumber = firstNumber;
Output
> let firstNumber = 1
> let secondNumber = 2
> let tempNumber = firstNumber;
> firstNumber = secondNumber;
> secondNumber = firstNumber;
> secondNumber = tempNumber
> firstNumber
> 2
> secondNumber
> 1
Implict swap with an Array
let firstNumber = 1
let secondNumber = 2
[firstNumber, secondNumber] = [secondNumber, firstNumber]
This technique leverages destructuring assignment
Output
> [firstNumber, secondNumber] = [secondNumber, firstNumber]
> firstNumber
2
> secondNumber
1
Bitwise XOR
let firstNumber = 1
let secondNumber = 2
firstNumber ^= secondNumber
secondNumber ^= firstNumber
firstNumber ^= secondNumber
Output
> firstNumber ^= secondNumber
> secondNumber ^= firstNumber
> firstNumber ^= secondNumber
> firstNumber
2
> secondNumber
1
Why does that last one work? Well because the number is stored in bytes and the bytes are composed of bits. The representation of 1
= 00000001
standard 8 bit byte and 2
= 00000010
Now doing an exclusive or XOR operation which means only 1 bit can be on or off when combined
Input 1 | Input 2 | Output |
---|---|---|
1 | 1 | 0 |
1 | 0 | 1 |
0 | 1 | 1 |
0 | 0 | 0 |
Going to use 4 bit nibbles for following binary math instead of longer 8 bit bytes above
So 1 XOR 2
= 3
0001
0010
----
0011
Then 2 XOR 3
= 1
0010
0011
----
0001
Then 3 XOR 1
= 2
0011
0001
----
0010
This solution seems insightful to me because it gets to the core of how data is bound by the base abstraction (this abstraction is pushed up from the physical legacy hardware of on/off switches)