yodacom
11/16/2016 - 2:16 PM

Recipe Factory - Example of Object Factory

Recipe Factory - Example of Object Factory

function recipeFactory(name, ingredients, steps) {
 var recipe = {};
   recipe.name = name;
   recipe.ingredients = ingredients;
   recipe.steps = steps;
   recipe.stepsHtml = function(){
       var result = '';
       result = result + '<ol>\n';
       this.steps.forEach(function(step){
           result = result + '<li>' + step + '</li>\n';
       });
       result = result + '</ol>';
       return result;
   },
   recipe.ingredientsHtml = function(){
       var result = '';
       result = result + '<ol>\n';
       result = result + this.ingredients.map(function(n){
               return '<li>' + n + '</li>';
           }).join('\n');
       result = result + '</ol>';
       return result;
   }


   return recipe;


}

// tests

function testRecipeFactory() {
  var grilledCheese = recipeFactory(
    'grilled cheese',
    ['2 slices bread', 'butter', '1 slice cheese'],
    ['Butter bread', 'Put cheese between bread', 'Toast bread on stove']
  );
  if (grilledCheese) {
    // `$` is a shortcut to the jQuery library, which
    // you'll learn about in the next unit.
    // Here, we're using jQuery to update elements in the HTML
    $('.js-recipe-name').text(grilledCheese.name);
    $('.js-ingredients').html(grilledCheese.ingredientsHtml());
    $('.js-steps').html(grilledCheese.stepsHtml());
  }
}

testRecipeFactory()