merge: added reduceRight & trim method (#961)

This commit is contained in:
Fahim Faisaal
2022-03-28 14:57:32 +06:00
committed by GitHub
parent b4fafb2479
commit 3b9af469f6
2 changed files with 19 additions and 18 deletions

View File

@ -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