diff --git a/String/ReverseWords.js b/String/ReverseWords.js index 089d6575d..9796c6208 100644 --- a/String/ReverseWords.js +++ b/String/ReverseWords.js @@ -1,16 +1,17 @@ +/** + * @function reverseWords + * @param {string} str + * @returns {string} - reverse string + */ const reverseWords = (str) => { if (typeof str !== 'string') { throw new TypeError('The given value is not a string') } - // Split string into words - // Ex. "I Love JS" => ["I", "Love", "JS"] - const words = str.split(' ') - // reverse words - // ["I", "Love", "JS"] => ["JS", "Love", "I"] - const reversedWords = words.reverse() - // join reversed words with space and return - // ["JS", "Love", "I"] => "JS Love I" - return reversedWords.join(' ') + + return str + .split(/\s+/) // create an array with each word in string + .reduceRight((reverseStr, word) => `${reverseStr} ${word}`, '') // traverse the array from last & create an string + .trim() // remove the first useless space } -export { reverseWords } +export default reverseWords diff --git a/String/test/ReverseWords.test.js b/String/test/ReverseWords.test.js index 830be369f..580857066 100644 --- a/String/test/ReverseWords.test.js +++ b/String/test/ReverseWords.test.js @@ -1,12 +1,6 @@ -import { reverseWords } from '../ReverseWords' - -describe('reverseWords', () => { - it('expects to reverse words to return a joined word', () => { - expect(reverseWords('I Love JS')).toBe('JS Love I') - expect(reverseWords('Hello World')).toBe('World Hello') - expect(reverseWords('The Algorithms Javascript')).toBe('Javascript Algorithms The') - }) +import reverseWords from '../ReverseWords' +describe('Testing the reverseWords function', () => { it.each` input ${123456} @@ -21,4 +15,10 @@ describe('reverseWords', () => { }).toThrow('The given value is not a string') } ) + + it('expects to reverse words to return a joined word', () => { + expect(reverseWords('I Love JS')).toBe('JS Love I') + expect(reverseWords('Hello World')).toBe('World Hello') + expect(reverseWords('The Algorithms Javascript')).toBe('Javascript Algorithms The') + }) })