-
Notifications
You must be signed in to change notification settings - Fork 25
/
(8 kyu) altERnaTIng cAsE = ALTerNAtiNG CaSe.js
62 lines (55 loc) · 1.17 KB
/
(8 kyu) altERnaTIng cAsE = ALTerNAtiNG CaSe.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
// 1 Plain solution
String.prototype.toAlternatingCase = function() {
let res = "";
for(let i = 0; i < this.length; i++) {
if (this[i] === this[i].toUpperCase()) {
res += this[i].toLowerCase();
} else {
res += this[i].toUpperCase();
}
}
return res;
}
// 2 Straightforward solution
String.prototype.toAlternatingCase = function(res = "") {
for(let i = 0; i < this.length; i++) {
res += this[i] === this[i].toUpperCase()
? this[i].toLowerCase()
: this[i].toUpperCase();
}
return res;
}
// 3 Optimized solution
String.prototype.toAlternatingCase = function() {
return [...this].map(
c => (c === c.toUpperCase()
? c.toLowerCase()
: c.toUpperCase()),
).join('');
}
// 4 Clever solution
String.prototype.toAlternatingCase = function() {
return this.
replace(
/[A-Za-z]/g,
x => x > "Z"
? x.toUpperCase()
: x.toLowerCase()
)
}
// 5 Coding golf
String
.prototype
.toAlternatingCase =
function() {
return this.
replace(
/[A-z]/g,
x => x[
`to${x > "Z"
? "Upper"
: "Lower"
}Case`
]()
)
}