Reputation: 379
I am trying to create a function to make this test pass
Here is my following code for my test cases:
var removeMiddle = require("./remove-middle");
test("Remove middle", function () {
var words = ["mouse", "giraffe", "queen", "window", "bottle"];
var expectedWords = ["mouse", "giraffe", "window", "bottle"];
var expectedOutput = ["queen"];
var output = removeMiddle(words);
expect(output).toEqual(expectedOutput);
expect(words).toEqual(expectedWords);
});
Here is my function that I created:
function removeMiddle(words) {
let index = [];
words.splice(2, 1);
for (let i = 0; i < words.length; i++) {
if (words[i] === "queen") {
index.push(words[i]);
}
}
return words;
}
module.exports = removeMiddle;
Right now my function just passed the second test case which is: expect(words).toEqual(expectedWords);
Upvotes: 0
Views: 39
Reputation: 20626
Firstly, you expect your output to be the word(s) removed. But you are returning the words
array from removeWords
. You probably can return index
.
Also, once you have spliced your words
array, queen will no more be a part of the array. So your for loop does nothing and index returns an empty array.
You can modify your code like this to get your expected output:
function removeMiddle(words) {
let index = [words[2]];
words.splice(2, 1);
return index;
}
But right now your code is a little hard coded, works only for a fixed length of array(5). You can do the following if you want a more generic solution.
function removeMiddle(words) {
if(words.length == 0) return [];
let index = [];
let middleElements = [];
if(words.length % 2 == 0){
console.log(words[Math.floor(words.length/2)]);
middleElements.push(words[Math.floor(words.length/2)]);
words.splice(words.length/2,1);
console.log(words[Math.floor(words.length/2)]);
middleElements.push(words[Math.floor(words.length/2)]);
words.splice(words.length/2,1);
}
else{
console.log(words.length/2);
middleElements.push(words[Math.floor(words.length/2)]);
words.splice(words.length/2,1);
}
return middleElements;
}
Upvotes: 1