Hello,
Im trying to solve the second part with this as code :
function numberOfWedges(lime) {
switch(lime) {
case 'small' : return 6;
case 'medium': return 8;
case 'large' : return 10;
}
}
export function limesToCut(wedgesNeeded, limes) {
let wedges = 0;
let neededLimes = 0;
while (wedges < wedgesNeeded -1 ) {
neededLimes += 1;
let lime = limes.shift();
wedges += numberOfWedges(lime)
}
return neededLimes
}
but in a case of a zero array of when the array is too short to find the wedget they answer is 1 too big.
Can someone help me to find the culprit ?
glennj
January 17, 2023, 7:49pm
2
You may need to add another condition into the while
statement to make sure that neededLimes
is not larger than the size of the limes
array.
Are you talking about this test?
test('works if no limes are available', () => {
expect(limesToCut(10, [])).toBe(0);
});
Either you can do what glennj has suggested. Or simpler still, you can consider adding a check to handle this as a special case.
In other words: you cannot shift()
anything if the array limes
is already empty.
still the same problem
` ``
limesToCut > uses up all limes if there are not enough to reach the target
``
Error: expect(received).toBe(expected) // Object.is equality
Expected: 7
Received: 8
export function limesToCut(wedgesNeeded,limes){
let limeUsed=0;
let totalLimes=limes.length;
function wedgeCount(size) {
switch(size){
case 'small':
return 6;
case 'medium':
return 8;
case 'large':
return 10;
}
}
while(wedgesNeeded>0){
wedgesNeeded-=wedgeCount(limes[0]);
limes.shift();
limeUsed+=1;
}
if(limeUsed>totalLimes){
return totalLimes;
}
return limeUsed;
}
Your answer is correct but the total number of elements available are 7 in that array and you are returning 8 as a answer that is why it is not working
Add below “if” construct in your code, before returning actual answer to solve the issue (And don’t forget to refactor variable name)
if(limeUsed>limes.length){
return limes.length;
} // here, I assume you are returning "limeUsed" variable
Happy coding!