File tree 4 files changed +72
-0
lines changed
4 files changed +72
-0
lines changed Original file line number Diff line number Diff line change @@ -13,4 +13,5 @@ Once inside, run the command below:
13
13
4 . Sentence Capitalization
14
14
5 . Palindromes
15
15
6 . Hamming Distance
16
+ 7 . Longest Word In a Sentence
16
17
Original file line number Diff line number Diff line change
1
+ // pick a solution and insert here to run the test.
2
+
3
+
4
+ function longestWord ( text ) {
5
+ var result = text . split ( ' ' ) . reduce ( ( maxLengthWord , currentWord ) => {
6
+ if ( currentWord . length > maxLengthWord . length ) {
7
+ return currentWord
8
+ } else {
9
+ return maxLengthWord
10
+ }
11
+ } , "" )
12
+ return result
13
+ }
14
+
15
+ module . exports = longestWord
Original file line number Diff line number Diff line change
1
+ // USING A FOR LOOP
2
+
3
+ function longestWord ( text ) {
4
+ let wordArray = text . split ( ' ' )
5
+ let maxLength = 0
6
+ let result = ''
7
+ for ( let i = 0 ; i < wordArray . length ; i ++ ) {
8
+ if ( wordArray [ i ] . length > maxLength ) {
9
+ maxLength = wordArray [ i ] . length
10
+ result = wordArray [ i ]
11
+ }
12
+ }
13
+ return result
14
+ }
15
+
16
+
17
+
18
+ // USING .REDUCE()
19
+
20
+ function longestWord ( text ) {
21
+ var result = text . split ( ' ' ) . reduce ( ( maxLengthWord , currentWord ) => {
22
+ if ( currentWord . length > maxLengthWord . length ) {
23
+ return currentWord
24
+ } else {
25
+ return maxLengthWord
26
+ }
27
+ } , "" )
28
+ return result
29
+ }
30
+
31
+
32
+ // USING .SORT()
33
+
34
+ function longestWord ( text ) {
35
+
36
+ var sortedArray = text . split ( ' ' )
37
+ . sort ( ( wordA , wordB ) => wordB . length - wordA . length )
38
+
39
+ return sortedArray [ 0 ]
40
+ }
Original file line number Diff line number Diff line change
1
+ const longestWord = require ( './index' )
2
+
3
+ test ( 'longestWord is a function' , ( ) => {
4
+ expect ( typeof longestWord ) . toEqual ( 'function' ) ;
5
+ } ) ;
6
+
7
+ test ( 'returns the longet word in a mixed case string of text' , ( ) => {
8
+ expect ( longestWord ( 'Top Shelf Web Development Training on Scotch' ) ) . toEqual ( 'Development' ) ;
9
+ } ) ;
10
+
11
+ test ( 'returns the longet word in a lowercase string' , ( ) => {
12
+ expect ( longestWord ( 'the ultimate guide to js algorithms' ) ) . toEqual ( 'algorithms' ) ;
13
+ } ) ;
14
+ test ( 'returns the longet word in an uppercase string' , ( ) => {
15
+ expect ( longestWord ( 'BUILDING FOR THE NEXT BILLION USERS' ) ) . toEqual ( 'BUILDING' ) ;
16
+ } ) ;
You can’t perform that action at this time.
0 commit comments