Average of items with different criteria

Asked

Viewed 26 times

0

I have this function that sums the prices of the items of a array

somaTotal() {

  let criterioPorIdpv = {};
  let criteriosComPrecos = [];

  // Parte 1: Monta um criterioPreco para cada criterio.
  for (let i in this.varia) {
      criteriosComPrecos.push({
          tipo: this.varia[i].tpCal,
          idPVs: this.varia[i].idPV,
          preco: 0.0
      });
  }

  // console.log(criteriosComPrecos);

  // Parte 2: Monta uma tabela de idPV para criterioPreco.
  for (let i in criteriosComPrecos) {
      let criterioPreco = criteriosComPrecos[i];
      for (let idPV in criterioPreco.idPVs) {
          criterioPorIdpv[criterioPreco.idPVs[idPV]] = criterioPreco;
      }
  }

  // console.log(criterioPorIdpv);

  // Parte 3: Acessa cada item da pizza, confere o seu valor e
  // o coloca no criterioPreco correspondente.
  for (let i in this.selectedVariation) {
      let item = this.selectedVariation[i];
      let crit = criterioPorIdpv[item.idPV];
      // console.log(crit);
      if (crit.tipo === "1") {
          let v = crit.preco;
          if (item.preco > v) crit.preco = item.preco;
      }else if (crit.tipo === "2") {
          let v = crit.preco;
          if (v == 0) {
            crit.preco = item.preco;
          }else if (item.preco < v) {
            crit.preco = item.preco;
          }
      } else if (crit.tipo === "3") {
          crit.preco += parseFloat(item.preco);

      }else if (crit.tipo === "4") {
          let v = crit.preco;
          if (v == 0) {
            crit.preco = item.preco;
          }else{
            // crit.preco = item.preco;
          }
      } else {
          throw new Error("Tipo inválido: " + crit.tipo);
      }
  }

  // Parte 4: Percorre todos os elementos criterioPreco
  // para obter o valor final.
  let total = 0;
  for (let i in criteriosComPrecos) {
      total += parseFloat(criteriosComPrecos[i].preco);
  }
  this.total = total;
  return total;
}

The problem is that I am not able to add in the following criterion: When the type is equal to "4" I want it to take the value of the items of this criterion why there will be several items with different criteria and I have no idea how to do.

  • Where this data is coming from... These criteria of type "4".. what is their structure.. It has as an example more , put more information..

  • Yes, the type "4" criterion comes from the first function’s... it searches inside an array of variations where "tpCal" represents the type of calculation, and I place it inside the "criteriosComPrecos" array by setting the "type" and "idPV" of the item!

No answers

Browser other questions tagged

You are not signed in. Login or sign up in order to post.