Skip to content

Replaced by reduceRight & trim method #961

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Mar 28, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
21 changes: 11 additions & 10 deletions String/ReverseWords.js
Original file line number Diff line number Diff line change
@@ -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
16 changes: 8 additions & 8 deletions String/test/ReverseWords.test.js
Original file line number Diff line number Diff line change
@@ -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}
Expand All @@ -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')
})
})
pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy