Dimitris Xydas Dimitris Xydas - 7 months ago 8
Javascript Question

Whats the most functional solution to farmers "print animals"?

What is the best way of printing the animals, while ensuring that future animals can be listed without changing the code much? My tryout is very amature...

var animals = ["Cows", "Chickens", "Pigs", "Horses"];

var printFarm = function(a, b, c, d){

console.log("You have " + a + " " + animals[0]);
console.log("You have " + b + " " + animals[1]);
console.log("You have " + c + " " + animals[2]);
console.log("You have " + d + " " + animals[3]);

};

printFarm(3, 6, 17, 54);

DHP DHP
Answer

Why not pass in an integer array to the function, and then do a loop with whatever the minimum number of items in either your animals array or your integer array is?

 var animals = ["Cows", "Chickens", "Pigs", "Horses"];

 var printFarm = function(animalCounts) {

      var index = Math.min(animals.length, animalCounts.length);

      for (var i = 0; i < index; i++) {
           console.log("You have " + animalCounts[i] + " " + animals[i];
      }
 }

 printFarm([1,2,3,4]);