Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Finding longest word, passing 9/10 tests, Why?

This is an task from codesignal.
It’s not a homework or something else, just I writed a code and now trying understand what’s wrong.
Let’s see task requirements.
Define a word as a sequence of consecutive English letters. Find the longest word from the given string.

Example.

For text = "Ready, steady, go!", the output should be
solution(text) = "steady".

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Well, now I’m sharing my code.

function solution(text) {
 let words = text.match(/\w+/g);
    
    let ml = Math.max(...words.map(el=>el.length))
    
    for(let i = 0; i < words.length; i++){
        if(words[i].length == ml){
            return words[i]
        }
    }
}

It’s passing all tests, except of one hide test. Now I opened that hide test it looks like this text: "ab-CDE-fg_hi". Expected output of this test is "CDE" .
Now I’m trying understand what’s the problem and why it’s not passing this test, can someone please explain me.

I’m newbie so please be more polite)

>Solution :

/\w+/ also includes an underscore, try to make the regex more precise, for example /[A-Za-z0-9]+/:

function solution(text) {
 let words = text.match(/[A-Za-z0-9]+/g);
    
    let ml = Math.max(...words.map(el=>el.length))
    
    for(let i = 0; i < words.length; i++){
        if(words[i].length == ml){
            return words[i]
        }
    }
}

console.log(solution("ab-CDE-fg_hi"));

You could also iterate the words immediately and find your max sooner:

function solution(text) {
  let max = '';
  for(const word of text.match(/[A-Za-z0-9]+/g)){
    if(max.length < word.length){
      max = word;
    }
  }
  return max;
}

console.log(solution("ab-CDE-fg_hi"));
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading