Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

114
Visualizações
Resize Columns To Fit Lengt - JavaScript - Math

Given a width of a grid and the target size of a column, I want to calculate a new size for the column, that is as close to the target size as possible.

For example:

gridSize: 10, targetSize: 9, newSize: 10
gridSize: 100, targetSize: 51, newSize: 50
gridSize: 20, targetSize: 6, newSize: 6.66667
...

Visualization:

enter image description here

If the target size is larger than the grid, it should default to the grid width.

Here is some code:

function calculateSize(gridWidth, targetSize){
         
  var newSize = 0;

  if(targetSize > gridWidth){

   // The target size is larger than the grid, default to maximum width

   newSize = gridWidth;

  }
  else{

    // Calculate new size, that is as close to the target size as possible

    var count = gridWidth / targetSize;
    var difference = Math.round(gridWidth / count) - gridWidth / count;
    
    // I don't know how to reach the desired result with these two values, maybe my approach is wrong

  }

  return newSize;

}

I am sure this is really easy, but Math is not my strong suit. Does anyone know how to calculate this? Thanks!

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

possibilities

function calculateSize(gridWidth, targetSize)
  {
  let inOut = { in:{}, out:{} }
  inOut.in.count     = Math.floor( gridWidth / targetSize )
  inOut.in.size      = Math.floor(gridWidth / inOut.in.count)
  inOut.in.sizefloat = gridWidth / inOut.in.count
  inOut.in.delta     = gridWidth - (inOut.in.count * inOut.in.size )

  inOut.out.size  = inOut.in.size +1
  inOut.out.count = inOut.in.count
  inOut.out.delta = (inOut.out.count * inOut.out.size ) - gridWidth

  inOut.best = (inOut.out.delta < inOut.in.delta) 
              ? `${inOut.out.count} columns of ${inOut.out.size} pixels (out)` 
              : `${inOut.in.count} columns  of ${inOut.in.size} pixels (in)` 

  return inOut
  }


console.log(  calculateSize(20,6)  )   
.as-console-wrapper {max-height: 100%!important;top:0 }

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda