File tree 2 files changed +14
-42
lines changed
2 files changed +14
-42
lines changed Original file line number Diff line number Diff line change @@ -16,24 +16,17 @@ function ReverseStringIterative (string) {
16
16
}
17
17
18
18
/**
19
- * JS disallows string mutation so we're actually a bit slower.
20
19
*
21
- * @complexity O(n)
20
+ * @author dev-madhurendra
21
+ * Reverses a number by converting it to a string.
22
+ *
23
+ * @param {string } str - The number to reverse.
24
+ * @returns {string } The reversed number.
25
+ *
26
+ * @example
27
+ * const reversed = reverseString("hello"); // Returns olleh
22
28
*/
23
- function ReverseStringIterativeInplace ( string ) {
24
- if ( typeof string !== 'string' ) {
25
- throw new TypeError ( 'The given value is not a string' )
26
- }
27
-
28
- const _string = string . split ( '' )
29
29
30
- for ( let i = 0 ; i < Math . floor ( _string . length / 2 ) ; i ++ ) {
31
- const first = _string [ i ]
32
- _string [ i ] = _string [ _string . length - 1 - i ]
33
- _string [ _string . length - 1 - i ] = first
34
- }
35
-
36
- return _string . join ( '' )
37
- }
30
+ const ReverseStringIterativeInplace = ( str ) => [ ...str ] . reverse ( ) . join ( '' )
38
31
39
32
export { ReverseStringIterative , ReverseStringIterativeInplace }
Original file line number Diff line number Diff line change @@ -35,31 +35,10 @@ describe('ReverseStringIterative', () => {
35
35
} )
36
36
37
37
describe ( 'ReverseStringIterativeInplace' , ( ) => {
38
- it ( 'expects to reverse a simple string' , ( ) => {
39
- expect ( ReverseStringIterativeInplace ( 'reverse' ) ) . toEqual ( 'esrever' )
40
- expect ( ReverseStringIterativeInplace ( 'some' ) ) . toEqual ( 'emos' )
41
- expect ( ReverseStringIterativeInplace ( 'string' ) ) . toEqual ( 'gnirts' )
42
- expect ( ReverseStringIterativeInplace ( 'The Algorithms Javascript' ) ) . toEqual ( 'tpircsavaJ smhtiroglA ehT' )
38
+ it . each ( [
39
+ [ 'hello' , 'olleh' ] ,
40
+ [ 'word' , 'drow' ]
41
+ ] ) ( 'reverse of %s is %s' , ( value , expected ) => {
42
+ expect ( ReverseStringIterativeInplace ( value ) ) . toBe ( expected )
43
43
} )
44
-
45
- it ( 'expects to reverse a simple string without capitalizing the first letter' , ( ) => {
46
- expect ( ReverseStringIterativeInplace ( 'Javascript' ) ) . toEqual ( 'tpircsavaJ' )
47
- } )
48
-
49
- it ( 'expects to return an empty string given an empty string' , ( ) => {
50
- expect ( ReverseStringIterativeInplace ( 'Javascript' ) ) . toEqual ( 'tpircsavaJ' )
51
- } )
52
-
53
- it . each `
54
- input
55
- ${ 123456 }
56
- ${ [ 1 , 2 , 3 , 4 , 5 , 6 ] }
57
- ${ { test : 'test' } }
58
- ${ null }
59
- ` (
60
- 'expects to throw a type error given a value that is $input' ,
61
- ( { input } ) => {
62
- expect ( ( ) => ReverseStringIterativeInplace ( input ) ) . toThrow ( 'The given value is not a string' )
63
- }
64
- )
65
44
} )
You can’t perform that action at this time.
0 commit comments