-
Notifications
You must be signed in to change notification settings - Fork 11
/
1-reverse-a-string.js
57 lines (46 loc) · 1.18 KB
/
1-reverse-a-string.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
/** Reverse a String
*
* Reverse the provided string.
* Your result must be a string.
*
* reverseString("hello")
* Output: "olleh"
*
* reverseString("HoWdy")
* Output: "ydWoH"
*
*/
// ✅ Solution: github.com/samanthaming/web-basics-challenge
// ✅ Try this challenge on freeCodeCamp.org
function reverseString(str) {
return str
.split('') // split the string into an array of individual letters
.reverse() // reverse the order of the array
.join(''); // convert the array back to a string
}
// ============================
// Using Reduce
// ============================
function reverseString2(str) {
return [...str].reduce((accumulator, current) => {
return current + accumulator;
});
// OR One-Liner
// return [...str].reduce((accumulator, current) => current + accumulator)
}
// ============================
// Using for-loop
// ============================
function reverseString3(str) {
let result = '';
for (let i = str.length - 1; i >= 0; i--) {
result += str[i];
}
return result;
}
// ============================
// Using sort
// ============================
function reverseString4(str) {
return str.split('').sort(() => 1).join('');
}