From 2a5e8c55eca72dd254bd227bb93d14cb8e7395a2 Mon Sep 17 00:00:00 2001 From: madhuredra Date: Mon, 2 Oct 2023 22:49:51 +0530 Subject: [PATCH] fix : added reverse string inplace --- String/ReverseString.js | 25 +++++++++---------------- String/test/ReverseString.test.js | 31 +++++-------------------------- 2 files changed, 14 insertions(+), 42 deletions(-) diff --git a/String/ReverseString.js b/String/ReverseString.js index df4fa7ada4..17240e71d1 100644 --- a/String/ReverseString.js +++ b/String/ReverseString.js @@ -16,24 +16,17 @@ function ReverseStringIterative (string) { } /** - * JS disallows string mutation so we're actually a bit slower. * - * @complexity O(n) +* @author dev-madhurendra +* Reverses a number by converting it to a string. +* +* @param {string} str - The number to reverse. +* @returns {string} The reversed number. +* +* @example +* const reversed = reverseString("hello"); // Returns olleh */ -function ReverseStringIterativeInplace (string) { - if (typeof string !== 'string') { - throw new TypeError('The given value is not a string') - } - - const _string = string.split('') - for (let i = 0; i < Math.floor(_string.length / 2); i++) { - const first = _string[i] - _string[i] = _string[_string.length - 1 - i] - _string[_string.length - 1 - i] = first - } - - return _string.join('') -} +const ReverseStringIterativeInplace = (str) => [...str].reverse().join('') export { ReverseStringIterative, ReverseStringIterativeInplace } diff --git a/String/test/ReverseString.test.js b/String/test/ReverseString.test.js index b9f29a57bf..0b4478f2cb 100644 --- a/String/test/ReverseString.test.js +++ b/String/test/ReverseString.test.js @@ -35,31 +35,10 @@ describe('ReverseStringIterative', () => { }) describe('ReverseStringIterativeInplace', () => { - it('expects to reverse a simple string', () => { - expect(ReverseStringIterativeInplace('reverse')).toEqual('esrever') - expect(ReverseStringIterativeInplace('some')).toEqual('emos') - expect(ReverseStringIterativeInplace('string')).toEqual('gnirts') - expect(ReverseStringIterativeInplace('The Algorithms Javascript')).toEqual('tpircsavaJ smhtiroglA ehT') + it.each([ + ['hello', 'olleh'], + ['word', 'drow'] + ])('reverse of %s is %s', (value, expected) => { + expect(ReverseStringIterativeInplace(value)).toBe(expected) }) - - it('expects to reverse a simple string without capitalizing the first letter', () => { - expect(ReverseStringIterativeInplace('Javascript')).toEqual('tpircsavaJ') - }) - - it('expects to return an empty string given an empty string', () => { - expect(ReverseStringIterativeInplace('Javascript')).toEqual('tpircsavaJ') - }) - - it.each` - input - ${123456} - ${[1, 2, 3, 4, 5, 6]} - ${{ test: 'test' }} - ${null} - `( - 'expects to throw a type error given a value that is $input', - ({ input }) => { - expect(() => ReverseStringIterativeInplace(input)).toThrow('The given value is not a string') - } - ) })