Explicación de Peso raro
Objetivo de este acertijo:
Usar console.log()
para ver si el código se ejecuta y luego buscar los errores en el código.
Tutorial de la solución:
La función prepareRecipeCards()
ejecuta tres líneas de código como el programa principal. La segunda línea es printTotalWeight()
. Pero la salida no tiene sentido:
> Total ingredient weight: 7two1.5 kilos
Para ver qué está sucediendo en la función, agrega dos declaraciones console.log()
dentro del for loop en printTotalWeight()
.
En la parte superior del código, se importan dos variables en esta línea:
import {itemWeight, totalWeight} from 'debugging';
itemWeight
y totalWeight
son strings asistentes que se deben usar para este acertijo.
Primero, en la parte superior del for loop, imprime itemWeight + i.kilos
. Luego, en la parte inferior del for loop, imprime totalWeight + total
. La versión final de printTotalWeight()
debe ser así:
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');
}
Ahora cuando se ejecuta el código, vemos exactamente lo que sucede dentro del ciclo. Este es la nueva salida:
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
Ahora podemos ver que la propiedad kilos
de uno de los objects en el arreglo ingredients
es el string two
en vez del número 2
.
Solución del código de ejemplo:
(Pulsa a continuación 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 que se ejecuta antes del código del acertijo):
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: ',
}
);