Rewriting Tomato with modular functions

My tomato code was quite long and there are a few opportunities to improve

  1. Organize the tomato function
  2. Make reusable function for position increments
  3. Organize draw() loop

Step 1 - Organizing the tomato function

I broke down the drawing of tomato into 2 parts:

Before

function tomato(x, y, tr1, tr2) {
  ...
  
  //drawing circle
  ...
  
  //drawing calyx
  ...
}

After

function tomato(x, y, tr1, tr2) {
  drawTomatoCircle(x, y, tr1, tr2);
  drawCalyx(x, y, tr1, tr2);
}

function drawTomatoCircle(x, y, tr1, tr2){
 ...
}

function drawCalyx(x, y, tr1, tr2){
  ...
}

Step 2 - Make reusable function for position increments

The calculation of position increments along x and y axes are essentially the same operation with different parameters.

x += tr1 / 2; //increase x by radius of last tomato
if (xleft > 220) tr1 = 100 + random(100); //set w randomly
else tr1 = xleft;  //set w to whatever is left
      
x += tr1 / 2; //increase x by radius of current tomato
y += tr2 / 2;
if (yleft > 220) tr2 = 100 + random(100);
else tr2 = yleft;
    
y += tr2 / 2;

I turned it into a reusable function: posIncrement()

function posIncrement(pos, diameter, remainder, threshold){
  //increase pos by radius of last tomato
  pos += diameter / 2;  

  //set new diameter randomly
  if (remainder > threshold) diameter = 100 + random(100); 
    
  //set new diameter to whatever is left
  else diameter = remainder; 
  
  //increase pos by radius of new tomato
  pos += diameter / 2; 
}  

I then updated draw() loop to:

function draw() {
  ...

  while (yleft > 0) {
    ...

    posIncrement(y, tr2, yleft, 220);
   
    while (xleft > 0) {
      posIncrement(x, tr1, xleft, 220);
      tomato(x, y, tr1, tr2);
      xleft -= tr1; //reduce by width of current tomato
    }
    yleft -= tr2;
  }
}

Looking a lot cleaner, except it does not work anymore!

From console.log, I could see that x and y are not longer incrementing, and I recalled that:

<aside> 👉🏻

A function needs to return the value, or else the values are updated locally within the function.

And, in order to return multiple values, I need to use an array.

</aside>