[Exercism-JavaScript] Mixed Juices
Task: Replenish the lime wedge supply
A lot of Li Mei's creations include lime wedges, either as an ingredient or as part of the decoration. So when she starts her shift in the morning she needs to make sure the bin of lime wedges is full for the day ahead.
Implement the function limesToCut
which takes the number of lime wedges Li Mei needs to cut and an array representing the supply of whole limes she has at hand. She can get 6 wedges from a 'small'
lime, 8 wedges from a 'medium'
lime and 10 from a 'large'
lime. She always cuts the limes in the order in which they appear in the list, starting with the first item. She keeps going until she reached the number of wedges that she needs or until she runs out of limes.
Li Mei would like to know in advance how many limes she needs to cut. The limesToCut
function should return the number of limes to cut.
limesToCut(25, ['small', 'small', 'large', 'medium', 'small']);
// => 4
Solution 1
/**
* Calculates the number of limes that need to be cut
* to reach a certain supply.
*
* @param {number} wedgesNeeded
* @param {string[]} limes
* @returns {number} number of limes cut
*/
export function limesToCut(wedgesNeeded, limes) {
let i = 0;
let wedges = 0;
let wedgesHad = 0;
while (wedgesHad < wedgesNeeded) {
switch (limes[i]) {
case 'small':
wedges = 6;
break;
case 'medium':
wedges = 8;
break;
case 'large':
wedges = 10;
break;
}
wedgesHad += wedges;
if (i < limes.length) {
i++;
}
}
return i;
}
Result: timed out
Solution 2
/**
* Calculates the number of limes that need to be cut
* to reach a certain supply.
*
* @param {number} wedgesNeeded
* @param {string[]} limes
* @returns {number} number of limes cut
*/
export function limesToCut(wedgesNeeded, limes) {
let limesWedges = [];
for (let i = 0; i < limes.length; i++) {
let wedges = 0;
switch (limes[i]) {
case 'small':
wedges = 6;
break;
case 'medium':
wedges = 8;
break;
case 'large':
wedges = 10;
break;
}
limesWedges.push(wedges);
}
let i = 0;
let wedgesHad = 0;
while (wedgesHad < wedgesNeeded) {
wedgesHad += limesWedges[i];
if (i < limesWedges.length) {
i++;
}
}
return i;
}
Result: passed
Conclusion
- wrapping
switch
statement inwhile
loop → timed out - wrapping
switch
statement infor
loop → passed
According to the results, author thinks that wrapping switch
statement in while
loop is less efficient.