[Chartjs]-JavaScript. Trying to simplify code, maybe with loops?

2👍

Just forEach over the graficaConexiones.data.datasets array:

graficaConexiones.data.datasets.forEach(({ data }) => {
  data.push(randomData());
  if (data.length > dataLength) {
    data.shift();
  }
});

In full:

function add_data() {
  const { labels, datasets } = graficaConexiones.data;
  var today = new Date();
  var time = today.getHours() + ":" + today.getMinutes() + ":" + today.getSeconds();
  labels.push(time);
  if (labels.length > labelLength) {
    labels.shift();
  }
  datasets.forEach(({ data }) => {
    data.push(randomData());
    if (data.length > dataLength) {
      data.shift();
    }
  });
}

Or, if you’re not comfortable with destructuring:

function add_data() {
  const labels = graficaConexiones.data.labels;
  const datasets = graficaConexiones.data.datasets;
  var today = new Date();
  var time = today.getHours() + ":" + today.getMinutes() + ":" + today.getSeconds();
  labels.push(time);
  if (labels.length > labelLength) {
    labels.shift();
  }
  datasets.forEach((dataset) => {
    const data = dataset.data;
    data.push(randomData());
    if (data.length > dataLength) {
      data.shift();
    }
  });
}

Extracting repeated property accesses into variables first really helps reduce repeated code.

Since you aren’t passing any arguments to add_data, remove all arguments from its definition.

2👍

With async/await the function could be simplified to a loop:

  const delay = ms => new Promise(res => setTimeout(res, ms));

   function today() {
     const today = new Date();
     return today.getHours() + ":" + today.getMinutes() + ":" + today.getSeconds();
   }

  async function updateLoop() {
    const { datasets, labels } = graficaConexiones.data;

    for(let i = 0; i < Math.Infinity; i++) {
        for(const set of datasets)
           set.data.push(randomData());

        labels.push(today());

        for(const set of [...datasets, labels])
           if(set.length > dataLength) set.shift();

       graficaConexiones.update();
       await delay(500);
   }
 }

Leave a comment