While I've tackled similar exercises in the past and always managed to solve them, this time I'm facing a roadblock with something quite simple. I'm working on creating a function that retrieves the middle characters from each word in a string (if the word is of even length then you should find the middle two characters) and most of my code seems fine, except for when an empty string is passed as input.
This is how my code looks right now:
function getMiddleChars (str) {
let emptyArray = [];
let middleIndex = str.length / 2;
for(let i = 0; i < str.length; i++) {
if(str === "") {
return emptyArray;
} else if(str.length % 2 == 0){
return str.slice(middleIndex -1, middleIndex + 1);
}
}
return str.charAt(middleIndex);
}
// It should return [] when passed an empty string:
// AssertionError: expected '' to deeply equal []
I could really use some assistance here. Any help would be greatly appreciated. Thank you!
UPDATE:
function getMiddleChars (str) {
let solution = [];
let middleIndex = str.length / 2;
if(str === ""){
return [];
}
if(str.length % 2 === 0){
return solution.push(str.slice(middleIndex - 1, middleIndex + 1));
} else {
return solution.push(str.charAt(middleIndex));
}
}
Even with the modifications, it's still not functioning correctly. I was confident I could crack this puzzle, but now I feel completely lost.