• Home
  • Jobs
  • Courses
  • Questions
  • Teachers
  • For business
  • ES/EN

0

27
Views
How to get the middle character from a string with the right answer?

After some tries only one of this fonction gave me the right result in CodeWars. Can any one explain to me the reason please?

{
  //1. solution => wrong
  var middle = Math.round(s.length / 2); 
  s.length % 2 == 0 ? console.log(s[middle-1] + s[middle]) : console.log(s[middle-1]);

 //2. solution => correct
return (s.length%2 == 0 ? s.substr((s.length/2-1),2) : s.substr((s.length/2),1));
}  

and the result to solution 1 is: enter image description here

about 1 month ago ·

Juan Pablo Isaza

2 answers
Answer question

0

The first solution handles strings with an odd length incorrectly; it is returning the character before the middle s[middle-1] instead of the character in the middle s[middle] .

The second solution fixes that by getting the character at position (s.length/2), which corresponds to the value of middle in the first solution.

Update with additional issue from @evolutionxbox:

As @evolutionxbox pointed out, if your original solution was using console.log instead of return to output the results, that is also an issue. I assumed that you added that to view the results side by side.

about 1 month ago · Juan Pablo Isaza Report

0

The failed test(s) messages tell you that the returned value (the value received by the test code) was always undefined, since they state expected undefined to equal 'es'.

The problem with your 1st solution is that it prints the results to the console (by calling console.log) instead of returning the result with a return statement.

If you get rid of console.log calls and add a return statement, then the 1st solution is almost identical to the 2nd solution and it will pass most tests.

There is still a slight difference though, the 1st solution returns NaN if the input is an empty string, while the 2nd solution returns an empty string. So depending on the tests suite, the 1st solution might still not pass all the tests.

Run the code below to compare the results.

solution1 = (s) => {
  var middle = Math.round(s.length / 2);
  return s.length % 2 == 0 ? s[middle-1]+s[middle] : s[middle-1];
};

solution2 = (s) => {
  return (s.length%2 == 0 ? s.substr((s.length/2-1),2) : s.substr((s.length/2),1));
};

["", "x", "oz", "eye", "test", "--z--", "---uv---"].forEach(it =>
  console.log("solution1: '%s' solution2: '%s' for input '%s'", solution1(it), solution2(it), it)
);

about 1 month ago · Juan Pablo Isaza Report
Answer question
Find remote jobs
Loading

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post job Plans Our process Sales
Legal
Terms and conditions Privacy policy
© 2022 PeakU Inc. All Rights Reserved.