DEV Community

loading...

Discussion on: What’s your alternative solution? Challenge #54

Collapse
jpantunes profile image
JP Antunes

Using a few 'modern' ES5+ constructs, we can reduce the solution to four lines of code.

Annotated version:

const longestWord = input => {
    //remove any character that isn't alphabetic (\w) or a blank space (\s) from input 
    //and split the resulting string on blank spaces, ie: this -> 'two word(s)!' becomes -> ['two', 'words']
    const words = input.replace(/[^\w\s]/g,'').split(' ');
    let maxLen = 0;
    //iterate over words to find the size of the longest word by comparing each length to the previous maxLen
    for (const word of words) maxLen = Math.max(maxLen, word.length);
    //return all words whose length is maxLen
    return words.filter(e => e.length == maxLen);
}