When used according to the specification, this function has O(1) complexity*.
/** @function getLongestWord
* @param {String} s a string of words with the longest word in the first position.
* @returns the longest word in a string, if it is the first word in the string, or a random word that occupies the first position in the string otherwise.
*/constgetLongestWord=>(s='')=>s.split(' ')[0]getLongestWord('loooongggg sentence very Iam')// 'loooongggg'
* It doesn't because split probably has complexity O(n) or something.
Recently started digging my way through GHC libraries
importData.ListcmpLength::String->String->OrderingcmpLengthlr=compare(lengthr)(lengthl)findLongest::String->StringfindLongests=head.sortBy(cmpLength).words$smain::IO()main=doputStrLn(findLongest"Iam a verrrrry loooongggg sentence")
importData.ListlongerString::String->String->StringlongerStringlr=iflengthl>lengthrthenlelserfindLongest::String->StringfindLongests=foldr(\longestw->longerStringlongestw)""(wordss)main::IO()main=doputStrLn(findLongest"Iam a verrrrry loooongggg sentence")
Same thing, but using a reducer instead of sorting.
constgetLongestWordOf=(sentence='')=>{returnsentence.split(' ').reduce((longest,current)=>{returncurrent.length>longest.length?current:longest;})}getLongestWordOf('I am just another solution to the same problem');
It's pronounced Diane. I do data architecture, operations, and backend development. In my spare time I maintain Massive.js, a data mapper for Node.js and PostgreSQL.
CREATEORREPLACEFUNCTIONget_longest_word(valTEXT)RETURNSTEXTAS$$DECLARElongest_wordTEXT;BEGINSELECTstrsINTOlongest_wordFROMregexp_split_to_table(val,'\s+')ASstrsORDERBYchar_length(strs)DESCLIMIT1;RETURNlongest_word;END;$$LANGUAGEplpgsql;SELECTget_longest_word('a bc def ghij klm no p');
Latest comments (14)
Bro, but what if it's the following sentence:
"I am a 'very('!) long(?) 'sentence'...!!!!""
When used according to the specification, this function has O(1) complexity*.
* It doesn't because
splitprobably has complexity O(n) or something.Recently started digging my way through GHC libraries
perl
Go
It may not be the most eye perfect code however the perf are close to the reducer solution jsperf.com/longestwordjs/11
I would still go to with the reducer solution, but sometimes doing 'old' things works very nice
I also try with for loop / for of, I expected it to be way more faster than everything else but it didn't.
from jsperf.com/foreach-vs-reduce-vs-fo...
Learned something new regarding jsperf, thank you. ๐
Can I chime in with a quick C# and LINQ one liner?
Well, the return statement is a one liner :)
Ignoring punctuation and only considering spaces... ruby solution:
I know one of the tags is 'Javascript' but here is how I would do it in Python:
Same thing, but using a reducer instead of sorting.
EDIT: This approach seems to be faster than the sorting one! jsperf.com/longestwordjs/1
This is what I thought to do as well ๐
Good one, didn't think of reduce ๐
Awesome๐