2022-03-28 14:57:32 +06:00
|
|
|
/**
|
|
|
|
|
* @function reverseWords
|
|
|
|
|
* @param {string} str
|
|
|
|
|
* @returns {string} - reverse string
|
|
|
|
|
*/
|
2020-05-10 00:25:56 +05:30
|
|
|
const reverseWords = (str) => {
|
2020-10-04 14:38:48 -03:00
|
|
|
if (typeof str !== 'string') {
|
|
|
|
|
throw new TypeError('The given value is not a string')
|
|
|
|
|
}
|
2022-03-28 14:57:32 +06:00
|
|
|
|
|
|
|
|
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
|
2020-05-10 00:25:56 +05:30
|
|
|
}
|
|
|
|
|
|
2022-03-28 14:57:32 +06:00
|
|
|
export default reverseWords
|