mirror of
https://github.com/TheAlgorithms/JavaScript.git
synced 2025-07-05 16:26:47 +08:00
merge: added reduceRight
& trim
method (#961)
This commit is contained in:
@ -1,16 +1,17 @@
|
|||||||
|
/**
|
||||||
|
* @function reverseWords
|
||||||
|
* @param {string} str
|
||||||
|
* @returns {string} - reverse string
|
||||||
|
*/
|
||||||
const reverseWords = (str) => {
|
const reverseWords = (str) => {
|
||||||
if (typeof str !== 'string') {
|
if (typeof str !== 'string') {
|
||||||
throw new TypeError('The given value is not a string')
|
throw new TypeError('The given value is not a string')
|
||||||
}
|
}
|
||||||
// Split string into words
|
|
||||||
// Ex. "I Love JS" => ["I", "Love", "JS"]
|
return str
|
||||||
const words = str.split(' ')
|
.split(/\s+/) // create an array with each word in string
|
||||||
// reverse words
|
.reduceRight((reverseStr, word) => `${reverseStr} ${word}`, '') // traverse the array from last & create an string
|
||||||
// ["I", "Love", "JS"] => ["JS", "Love", "I"]
|
.trim() // remove the first useless space
|
||||||
const reversedWords = words.reverse()
|
|
||||||
// join reversed words with space and return
|
|
||||||
// ["JS", "Love", "I"] => "JS Love I"
|
|
||||||
return reversedWords.join(' ')
|
|
||||||
}
|
}
|
||||||
|
|
||||||
export { reverseWords }
|
export default reverseWords
|
||||||
|
@ -1,12 +1,6 @@
|
|||||||
import { reverseWords } from '../ReverseWords'
|
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')
|
|
||||||
})
|
|
||||||
|
|
||||||
|
describe('Testing the reverseWords function', () => {
|
||||||
it.each`
|
it.each`
|
||||||
input
|
input
|
||||||
${123456}
|
${123456}
|
||||||
@ -21,4 +15,10 @@ describe('reverseWords', () => {
|
|||||||
}).toThrow('The given value is not a string')
|
}).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')
|
||||||
|
})
|
||||||
})
|
})
|
||||||
|
Reference in New Issue
Block a user