Home > Software engineering >  Is there a way to use a for loop to create n functions in js
Is there a way to use a for loop to create n functions in js

Time:04-04

I have a section of code where I have 3 different functions to create 3 egg sprites which only differ in numbers.

let egg1, egg2, egg3

function makeegg1(){

  egg1 = new Image();
  egg1.src = eggs[0].src;

  ctx.clearRect(eggs[0].x, eggs[0].y, 10 * 3, 14 * 3);

  egg1.onload = function(){
    ctx.drawImage(egg1, eggs[0].x, eggs[0].y, 10 * 3, 14 * 3);}

    ctx.imageSmoothingEnabled = false; 
    ctx.mozImageSmoothingEnabled = false; 
    ctx.webkitImageSmoothingEnabled = false; 
    ctx.msImageSmoothingEnabled = false; 

  collect();
  updateeggcoords(1);
}

var egg1int = setInterval(makeegg1, 1000);

//repeat this makeegg[n] function and egg[n]int variable 2 more times with n=2 and n=3
//for the list, its n-1, so 0, 1 and 2

I want to optimize this strip of code by putting it into a for loop, so I would only have to write one function instead of copying and pasting 2 more. For instance, if I were to want to create more egg sprites, this copying and pasting will get redundant, and impractical for large amounts of egg sprites, say 50.

I have tried making an array, but I am unsure how to store the functions using such an array. Guidance on how to do this would be appreciated. If you need further clarification, I will provide it.

CodePudding user response:

I think what you should do is making your function to be reusable with different egg sprite. I would change your function into something like this

function makeEgg(index){

  const egg = new Image();
  const eggImage = eggs[index - 1];

  egg.src = eggImage.src;

  ctx.clearRect(eggImage.x, eggImage.y, 10 * 3, 14 * 3);

  egg.onload = function(){
    ctx.drawImage(egg1, eggImage.x, eggImage.y, 10 * 3, 14 * 3);}

    ctx.imageSmoothingEnabled = false; 
    ctx.mozImageSmoothingEnabled = false; 
    ctx.webkitImageSmoothingEnabled = false; 
    ctx.msImageSmoothingEnabled = false; 

  collect();
  updateeggcoords(index);
}

for (let i=1; i <=3; i  = 1) {
    makeEgg(i);
}

The changes are:

  • Add index as params for the function
  • Refer to index in the function instead of hard-coded 0

By doing this, you are able to reuse this function as many time as you like

  • Related