Explicação de Peso estranho
Objetivo deste desafio:
Use console.log()
para observar como o código está sendo executado e encontrar os erros do código.
Passo a passo da solução:
A função prepareRecipeCards()
executa três linhas do código como o programa principal. A segunda linha é printTotalWeight()
. Mas o resultado não faz sentido:
> Total ingredient weight: 7two1.5 kilos
Para ver o que está acontecendo na função adicione dois comandos console.log()
dentro do laço for em printTotalWeight()
.
Na parte superior do código, são importadas duas variáveis nessa linha:
import {itemWeight, totalWeight} from 'debugging';
itemWeight
e totalWeight
são strings auxiliares a serem usadas neste desafio.
Primeiro, na parte superior do laço for, registre itemWeight + i.kilos
. Em seguida, na parte inferior do laço, registre totalWeight + total
. A versão final de printTotalWeight()
deve ficar assim:
function printTotalWeight() {
let total = 0;
for (let i of ingredients) {
console.log(itemWeight + i.kilos);
total += i.kilos;
console.log(totalWeight + total);
}
print('Total ingredient weight: ' + total + ' kilos');
}
Agora quando o código for executado, veremos exatamente o que está acontecendo dentro do laço. Veja o novo resultado:
Item Weight: 4
> Total Weight: 4
> Item Weight: 2
> Total Weight: 6
> Item Weight: 1
> Total Weight: 7
> Item Weight: two
> Total Weight: 7two
> Item Weight: 1.5
> Total Weight: 7two1.5
> Total ingredient weight: 7two1.5 kilos
Agora podemos ver que a propriedade kilos
de um dos objetos na array ingredients
é a string two
em vez do número 2
.
Solução do código de exemplo:
(Toque abaixo para revelar)
import {addIngredient} from 'cookbook';
import {itemWeight, totalWeight} from 'debugging';
let ingredients = [
{
name: 'potatoes',
kilos: 4,
},
{
name: 'carrots',
kilos: 2,
},
{
name: 'onions',
kilos: 1,
},
{
name: 'chickens',
kilos: 'two',
},
];
let leeks = {name: 'leeks', kilos: 1.5};
function printTotalWeight() {
let total = 0;
for (let i of ingredients) {
console.log(itemWeight + i.kilos);
total += i.kilos;
console.log(totalWeight + total);
}
print('Total ingredient weight: ' + total + ' kilos');
}
function printIngredient(ingredient) {
print(ingredient.kilos + ' kilos ' + ingredient.name);
}
function prepareRecipeCards() {
try {
addIngredient(leeks);
printTotalWeight();
ingredients.forEach(printIngredient());
} catch (e) {
console.log(e);
}
}
prepareRecipeCards();
Código adicional Código adicional (código oculto executado antes do código do desafio):
function _addIngredient({name, kilos}) {
if (isNaN(kilos)) {
throw new Error(`kilos must be a number. got ${kilos} instead`);
}
ingredients.push({
name,
kilos,
});
console.log(`Added ${name}, ${kilos} kilos, to the ingredients list.`);
}
defineModule(
'cookbook',
{
addIngredient: _addIngredient,
}
);
defineModule(
'debugging',
{
itemWeight: 'Item Weight: ',
totalWeight: 'Total Weight: ',
}
);