1

I've done similar exercises to this one before and always figured it out, but I'm stuck with the silliest thing. I'm doing the classic "get the middle character' (This function takes a string and returns an array containing the middle characters of each word. If the word is of even length then you should find the middle two characters) and I think my code should work well for all tests but the empty string one. When an empty string "" is passed, it should return an empty array [], an even specifying to do so, it returns "".

This is my code so far:

function getMiddleChars (str) {
 let empty =[];
 let middle = str.length /2;
 for(let i =0; i<str.length; i++){
  if(str === ""){
    return empty;
  }else if(str.length %2 == 0){
     return str.slice(middle -1, middle +1);
   }
 }
 return str.charAt(middle);

}
returns [] when passed "":
     AssertionError: expected '' to deeply equal []

Could anyone give me a hand? Thanks in advance.

EDITED:

function getMiddleChars (str) {
 let solution = [];
 let middle = str.length /2;
  if(str === ""){
   return [];
 } if(str.length %2 === 0){
   return solution.push(str.slice(middle -1, middle +1));
 } else {
   return solution.push(str.charAt(middle));
 }
}

Still won't work. I was pretty sure I could figure this out and I'm lost now.

3
  • 3
    First line of function -> if (str === "") return []; Commented Mar 28, 2018 at 16:31
  • 1
    An empty string has a length of 0. Therefore, your for loop never executes and it skips the return empty and goes straight to return str.charAt(middle). Middle is 0, so the character at 0 is an empty string ''. Commented Mar 28, 2018 at 16:35
  • 1
    Note that your function returns no arrays at all, even for "good" strings. Commented Mar 28, 2018 at 16:35

2 Answers 2

2

Split the string to words, iterate with Array.map(), and return the middle characters for each word:

function getMiddleChars(str) {
  return str ? str.split(/\s+/).map((word) => {
    const middle = (word.length - 1) / 2;

    return word.substring(Math.floor(middle), Math.ceil(middle) + 1);
  }) : [];
}

console.log(getMiddleChars('cats')); // ["a", "t"]
console.log(getMiddleChars('cat')); // ["a"]
console.log(getMiddleChars('a')); // ["a"]
console.log(getMiddleChars('hello world')); // ["l", 'r']
console.log(getMiddleChars('')); // []

Sign up to request clarification or add additional context in comments.

Comments

2

You could do this as the first step of your function:

if(str === "")
{
    return [];
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.