How can i optimize this chain of if/else statement?

hello i want to optimize this code.
I thought that i can use the switch statement, but i don’t know how to implement it:

//function setup() {
  createCanvas(400, 400);
}

function draw() {
  background(220);
  
  let s = second();
  let mt = minute();
  let h = hour();
  translate(-100,150);

  //check if the second/minute/hour need a 0 before
  if(h < 10 && mt < 10 && s < 10){
    text('0'+h+'/'+'0'+mt+'/'+'0'+s,360,0);
  }
  else if(h < 10 && mt < 10){
    text('0'+h+'/'+'0'+mt+'/'+s,360,0);
  }
  else if(s < 10 && mt < 10){
    text(h+'/'+'0'+mt+'/'+'0'+s,360,0);
  }
  else if(h < 10 && s < 10){
    text('0'+h+'/'+mt+'/'+'0'+s,360,0);
  }
  else if(h < 10){
    text('0'+h+'/'+mt+'/'+s,360,0);
  }
  else if(mt < 10){
    text(h+'/'+'0'+mt+'/'+s,360,0);
  }
  else if(s < 10){
    text(h+'/'+mt+'/'+'0'+s,360,0);
  }
  else{
    text(h+'/'+mt+'/'+s,360,0);
  }
}

Hi, you can use the nf() function to format your string.

thank you for your help i try to use it right now

let times = [];
//---------------------------------------
function setup() {
  createCanvas(400, 400);
}
//---------------------------------------
function draw() {
  background(220);
  times[0] = hour();
  times[1] = minute();
  times[2] = second();
  times = nf(times, 2);
  //-------------------
  text(times, 10, 30);  
  text(times[0]+" : "+times[1]+" : "+times[2],10,60);
}

as he said :slight_smile: could look like this…
since nf can gobble up arrays too, it might make sense to use one.

1 Like