File tree Expand file tree Collapse file tree 1 file changed +42
-0
lines changed
udemy-interview-bootcamp-course Expand file tree Collapse file tree 1 file changed +42
-0
lines changed Original file line number Diff line number Diff line change
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 ;
You can’t perform that action at this time.
0 commit comments