Skip to content

Commit 25027bd

Browse files
author
Connor Leech
committed
add reverse string
1 parent 5c05ab2 commit 25027bd

File tree

1 file changed

+42
-0
lines changed

1 file changed

+42
-0
lines changed
Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
/*
2+
3+
Given a string, return a new string with the reversed
4+
order of characters
5+
6+
reverse('apple') => 'elppa'
7+
*/
8+
9+
function reverse(str){
10+
let result = '';
11+
for(var i = str.length; i >= 0; i--){
12+
result += str.charAt(i);
13+
}
14+
return result;
15+
}
16+
17+
// use built in array and string
18+
function reverseSolution1(str){
19+
return str.split('')
20+
.reverse()
21+
.join('');
22+
}
23+
24+
// use for ... of and prepend
25+
function reverseSolution2(str){
26+
let result = '';
27+
for(let char of str){
28+
result = char + result;
29+
}
30+
return result;
31+
}
32+
33+
// use array reduce
34+
function reverseSolution3(str){
35+
return str
36+
.split('')
37+
.reduce((result, letter)=> letter + result, '');
38+
}
39+
40+
console.log(reverseSolution3('hello'));
41+
42+
module.exports = reverse;

0 commit comments

Comments
 (0)