'Eloquent JavaScript Book : don't understand the example
in chapter 3, there is this Hummus recipe example, what I really don't understand is code like this:
const hummus = function(factor) {
const ingredient = function(amount, unit, name) {
let ingredientAmount = amount * factor;
if (ingredientAmount > 1) {
unit += "s";
}
console.log(`${ingredientAmount} ${unit} ${name}`);
};
ingredient(1, "can", "chickpeas");
ingredient(0.25, "cup", "tahini");
ingredient(0.25, "cup", "lemon juice");
ingredient(1, "clove", "garlic");
ingredient(2, "tablespoon", "olive oil");
ingredient(0.5, "teaspoon", "cumin");
};
I added a couple of console.log to try to better track the progress and to understand what is actually happening here, but i couldn't wrap my head around it. I mean what is the expected outcome here?
Solution 1:[1]
The goal of the example is to show you the functions scope. By passing the fixed argument to the hummus function you could return some new literal object that will be calculated by using your inner function and outer function argument factor to calculate the final result.
Solution 2:[2]
just add hummus(amount) to get outputs of ingredients
hummus(5); to call function at end of the code
output: 5 cans chickpeas 1.25 cups tahini 1.25 cups lemon juice 5 cloves garlic 10 tablespoons olive oil 2.5 teaspoons cumin
Solution 3:[3]
This is more detailed explanation based on Ahmed Taha's explanation:
const hummus = function(factor) { //this function needs to be called
//this function automatically called when hummus is called
const ingredient = function(amount, unit, name) {
//the amount of ingredients you need based on the factor
let ingredientAmount = amount * factor;
if (ingredientAmount > 1) {
unit += "s";
}
console.log(`${ingredientAmount} ${unit} ${name}`);
};
//these are the ingredients you need to make the hummus
ingredient(1, "can", "chickpeas");
ingredient(0.25, "cup", "tahini");
ingredient(0.25, "cup", "lemon juice");
ingredient(1, "clove", "garlic");
ingredient(2, "tablespoon", "olive oil");
ingredient(0.5, "teaspoon", "cumin");
};
//The ingredients you need to make 5 portions of hummus
hummus(5)
The output will be:
5 cans chickpeas
1.25 cups tahini
1.25 cups lemon juice
5 cloves garlic
10 tablespoons olive oil
2.5 teaspoons cumin
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Mrsevic |
| Solution 2 | Ahmed Taha |
| Solution 3 | Steve_ |
