You are on page 1of 1

11) The below script has some troubles getting the numbers right.

What could be
wrong?
var fruitSaladRecipe = "2 apples, papaya, coconut, 5 oranges, apple, banana",
ingredients = fruitSaladRecipe.split(/,\s+/),
ingredientHash = {},
num = 0; // Total number of fruits
for (var i=0 ; i<ingredients.length ; i++) {
var ingredient = ingredients[i],
fruitType = ingredient.match(/(\w+)$/)[1].replace(/s$/, ""),
numPieces;
if (/^\d+/.test(ingredient)) {
var num = ingredient.match(/^(\d+)/)[1];
numPieces = parseInt(num, 10);
}else{
numPieces = 1;
}
if (/^(?:banana)$/.test(fruitType)) {
// Speaking of bananas, let's add some more! Those things are delicious!
numPieces *= 2;
}
num += numPieces;
if (fruitType in ingredientHash) {
numPieces += ingredientHash[fruitType];
}
ingredientHash[fruitType] = numPieces;
}
var message = num + " fruit(s) in total:";
for (var ingredient in ingredientHash) {
if (ingredientHash.hasOwnProperty(ingredient)) {
message += " " + ingredientHash[ingredient] + " " + ingredient + "(s)";
}
}
alert(message);
The total will be incremented twice for fruit types that have already been e
ncountered in the list.
The lack of block scope in Javascript causes the second var num assignment t
o overwrite the first one.
The numbers are interpreted as binary because the parseInt function is calle
d with a wrong 'radix' parameter.
A for-in loop can only be used with arrays. The behavior is undefined when u
sed with objects.
An error in one of the regular expressions causes apples and oranges to be c
onsidered the same fruit type.
12) What is the return value of setInterval?
An object that make is possible to queue up messages/objects for the next in
vocation of the function passed to setInterval.
An ID that can be used with clearInterval to stop the interval.
An opaque object that can be used with clearTimeout to stop the interval.
Whatever is returned from the first invocation of the function passed to set
Interval.

You might also like