-
-
Notifications
You must be signed in to change notification settings - Fork 44
/
reversed-strings.js
86 lines (64 loc) · 1.71 KB
/
reversed-strings.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
82
83
84
function reverseString(str){
// a place to store the reversed string
// initialized to the empty string
let reversed = '';
// iterate over the string in reverse
for (let i = str.length - 1; i >= 0; i--) {
// store the current letter in a variable
const letter = str[i];
// append the letter to the reversed string
reversed += letter;
}
// return the reversed string
return reversed;
}
function reverseString(str){
let reversed = '';
for (let i = 0; i < str.length; i++) {
const letter = str[i];
reversed = letter + reversed;
}
return reversed;
}
function reverseString(str) {
return str
.split('')
.reverse()
.join('');
}
function reverseString(str) {
let reversed = '';
[].forEach.call(str, (letter) => {
reversed = letter + reversed;
});
// Array.prototype.forEach.call(str, (letter) => {
// reversed = letter + reversed;
// });
// str.split('').forEach((letter) => {
// reversed = letter + reversed;
// });
// [...str].forEach((letter) => {
// reversed = letter + reversed;
// });
return reversed;
}
function reverseString(str) {
return [].reduce.call(str, (reversed, letter) => {
return letter + reversed;
}, '');
}
function reverseString(str) {
return [].reduceRight.call(str, (reversed, letter) => {
return reversed + letter;
}, '');
}
// function reverseString([a, ...b]) {
// return b.length ? reverseString(b) + a : a;
// }
// const [a, ...b] = 'world';
// console.log(a);
// console.log(b);
console.log(reverseString('world'), 'dlrow');
// Use 2 pointer approach to reverse the string
// .pop() then poped value + reverse :D
// reverseString = x = ([a, ...b]) => b.length ? x(b) + a : a;