-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathswapping.js
71 lines (60 loc) · 1.02 KB
/
swapping.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
/**
* swaping of 2 numbers without 3rd var
*/
let a = 1,
b = 2;
// ------- way 1 --------
a = a + b
b = a - b
a = a - b
console.log('A', a, 'B', b);
// ------- way 2 --------
a += b
b = a - b
a -= b
console.log('A', a, 'B', b);
// ------- way 3 --------
a = a ^ b
b = a ^ b
a = a ^ b
console.log('A', a, 'B', b);
// ------- way 4 --------
a ^= b;
b ^= a;
a ^= b;
console.log('A', a, 'B', b);
/**
* Single line swapping with addition 1
*/
a = b + (b=a, 0);
console.log('A', a, 'B', b);
/**
* Single line swapping with addition 2
*/
b=a+(a=b)-b;
console.log('A', a, 'B', b);
/**
* Single line swapping with XOR
*/
a = a^b^(b^=(a^b));
console.log('A', a, 'B', b);
/**
* Classic one-line method
*/
a = [b, b=a][0];
console.log('A', a, 'B', b);
/**
* Using ES6 self executing arrow functions
*/
b = (a=>a)(a,a=b);
console.log('A', a, 'B', b);
/**
* ES5+ immediately invoked function
*/
b = (function(a){ return a })(a, a=b);
console.log('A', a, 'B', b);
/**
* ES6+ method
*/
[a, b] = [b, a];
console.log('A', a, 'B', b);