-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathreverseString.js
81 lines (71 loc) · 1.67 KB
/
reverseString.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
72
73
74
75
76
77
78
79
80
81
// ===============================================================
// Return a string in reverse.
// ===============================================================
// Clean code. easy to explain
function reverseString(str) {
const strArr = str.split('');
strArr.reverse();
return strArr.join('');
}
// One liner.
function reverseString(str) {
return str.split('').reverse().join('');
}
// Using a decreasing forLoop
function reverseString(str) {
let revString = '';
for (let i = str.length - 1; i >= 0; i--) {
revString = revString + str[i];
}
return revString;
}
// Using an increasing forLoop
function reverseString(str) {
let revString = '';
for (let i = 0; i <= str.length - 1; i++) {
revString = str[i] + revString;
}
return revString;
}
// Using forOf loop
function reverseString(str) {
let revString = '';
for (let char of str) {
revString = char + revString;
}
return revString;
}
// For Each loop
function reverseString(str) {
let revString = '';
str.split('').forEach(function (char) {
revString = char + revString;
});
return revString;
}
// For each ES6
function reverseString(str) {
let revString = '';
str.split('').forEach((char) => (revString = char + revString));
return revString;
}
// Using REDUCE
function reverseString(str) {
return str.split('').reduce(function (revString, char) {
return char + revString;
}, '');
}
// Using reduce and ES6
function reverseString(str) {
return str.split('').reduce((revString, char) => char + revString, '');
}
var reverseString = function (s) {
let i = 0,
j = s.length - 1;
while (i < j) {
[s[i], s[j]] = [s[j], s[i]];
i++;
j--;
}
return s;
};