Skip to content

Commit 3b9af46

Browse files
authored
merge: added reduceRight & trim method (TheAlgorithms#961)
1 parent b4fafb2 commit 3b9af46

File tree

2 files changed

+19
-18
lines changed

2 files changed

+19
-18
lines changed

String/ReverseWords.js

+11-10
Original file line numberDiff line numberDiff line change
@@ -1,16 +1,17 @@
1+
/**
2+
* @function reverseWords
3+
* @param {string} str
4+
* @returns {string} - reverse string
5+
*/
16
const reverseWords = (str) => {
27
if (typeof str !== 'string') {
38
throw new TypeError('The given value is not a string')
49
}
5-
// Split string into words
6-
// Ex. "I Love JS" => ["I", "Love", "JS"]
7-
const words = str.split(' ')
8-
// reverse words
9-
// ["I", "Love", "JS"] => ["JS", "Love", "I"]
10-
const reversedWords = words.reverse()
11-
// join reversed words with space and return
12-
// ["JS", "Love", "I"] => "JS Love I"
13-
return reversedWords.join(' ')
10+
11+
return str
12+
.split(/\s+/) // create an array with each word in string
13+
.reduceRight((reverseStr, word) => `${reverseStr} ${word}`, '') // traverse the array from last & create an string
14+
.trim() // remove the first useless space
1415
}
1516

16-
export { reverseWords }
17+
export default reverseWords

String/test/ReverseWords.test.js

+8-8
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,6 @@
1-
import { reverseWords } from '../ReverseWords'
2-
3-
describe('reverseWords', () => {
4-
it('expects to reverse words to return a joined word', () => {
5-
expect(reverseWords('I Love JS')).toBe('JS Love I')
6-
expect(reverseWords('Hello World')).toBe('World Hello')
7-
expect(reverseWords('The Algorithms Javascript')).toBe('Javascript Algorithms The')
8-
})
1+
import reverseWords from '../ReverseWords'
92

3+
describe('Testing the reverseWords function', () => {
104
it.each`
115
input
126
${123456}
@@ -21,4 +15,10 @@ describe('reverseWords', () => {
2115
}).toThrow('The given value is not a string')
2216
}
2317
)
18+
19+
it('expects to reverse words to return a joined word', () => {
20+
expect(reverseWords('I Love JS')).toBe('JS Love I')
21+
expect(reverseWords('Hello World')).toBe('World Hello')
22+
expect(reverseWords('The Algorithms Javascript')).toBe('Javascript Algorithms The')
23+
})
2424
})

0 commit comments

Comments
 (0)