File tree Expand file tree Collapse file tree 2 files changed +14
-42
lines changed Expand file tree Collapse file tree 2 files changed +14
-42
lines changed Original file line number Diff line number Diff line change @@ -16,24 +16,17 @@ function ReverseStringIterative (string) {
1616}
1717
1818/**
19- * JS disallows string mutation so we're actually a bit slower.
2019 *
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
2228 */
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 ( '' )
2929
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 ( '' )
3831
3932export { ReverseStringIterative , ReverseStringIterativeInplace }
Original file line number Diff line number Diff line change @@ -35,31 +35,10 @@ describe('ReverseStringIterative', () => {
3535} )
3636
3737describe ( '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 )
4343 } )
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- )
6544} )
You can’t perform that action at this time.
0 commit comments