forked from TheAlgorithms/JavaScript
- Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathReverseWords.js
More file actions
Latest commit
17 lines (15 loc) · 495 Bytes
/
Copy pathReverseWords.js
File metadata and controls
17 lines (15 loc) · 495 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
/**
* @function reverseWords
* @param {string} str
* @returns {string} - reverse string
*/
constreverseWords=(str)=>{
if(typeofstr!=='string'){
thrownewTypeError('The given value is not a string')
}
returnstr
.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
}
exportdefaultreverseWords