VisualXZ
VisualXZ

Reputation: 213

Return empty array when empty string is passed

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.

Upvotes: 1

Views: 3240

Answers (2)

Ori Drori
Ori Drori

Reputation: 191976

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('')); // []

Upvotes: 2

Christos
Christos

Reputation: 53958

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

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

Upvotes: 2

Related Questions