-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathStringReverse.js
72 lines (59 loc) · 1.56 KB
/
StringReverse.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
//Method 1 - using split(), reverse() and join()
function reverseStr1(str) {
return str.split("").reverse().join('')
}
console.log(reverseStr1("hello"))
//Method 2- for loop from the start
function reverseStr2(str) {
const strArr = str.split('')
let reverse = ''
for(let i = 0 ; i <= strArr.length - 1 ; i ++)
{
reverse = strArr[i] + reverse
}
return reverse
}
console.log(reverseStr2("hello"))
//Method 3 - for loop from the end - fastest way
function reverseStr3(str) {
const strArr = str.split('')
let reverse = ''
for(let i = strArr.length - 1 ; i >= 0 ; i--) {
reverse += strArr[i]
}
return reverse;
}
console.log(reverseStr3("hello"))
//Method 4 - ES6 spread operator
function reverseStr4(str) {
return [...str].reverse().join('')
}
console.log(reverseStr4("hello"))
//Method 5
function reverseStr5(str) {
return Array.from(str).reverse().join('')
}
console.log(reverseStr5("hello"))
//Method 6 - higher order function reduce()
function reverseStr6 (str) {
return str.split('').reduce((reverse, char) => char + reverse, '')
}
console.log(reverseStr6("hello"))
//Method 7 - using forEach
function reverseStr7 (str) {
let reverseStr = ''
str.split('').forEach(char => {
reverseStr = char + reverseStr
})
return reverseStr;
}
console.log(reverseStr7("hello"))
//Method 8 - using for of loop
function reverseStr8 (str) {
let reverseStr = ''
for(let char of str) {
reverseStr = char + reverseStr
}
return reverseStr;
}
console.log(reverseStr8("hello"))