Domanda

All right people, I've got a slight performance bottle neck.

Basically I have a graph that consists of a screen div ("screen") and a chart div ("chart"), when this graph finishes rendering it checks to see what scale it needs to set on the chart in order to have the chart fit inside the screen. The problem is that whatever scale I come up with needs to be an exponent of 1.2. In other words you need to be able to get to the number of the new scale by taking 1.2 to the power of some number.

This function is what calculates the scale I need.

fitScale = function (width, height)
{
  var scale = 1,
      gWidth = graph.element.offsetWidth,
      gHeight = graph.element.offsetHeight;
  while (gWidth > width * scale && gHeight > height * scale)
    scale *= 1.2;
  while (gWidth < width * scale || gHeight < height * scale)
    scale /= 1.2;
  return 900 / scale;
}

The problem is that this sucks...

What it's doing is getting the chart size (width, height) and the screen size (gWidth, gHeight) and looping through a new scale until it hits the right number.

First it makes the scale bigger until at least one dimension of the chart times the scale is bigger than one dimension of the screen.

Than it loops back to make sure that both the dimensions of chart * scale are at least a little bit smaller than the screen.

I'de like to perform this action with just one math calculation. Maybe by calculating a snug fit and then by rounding down, but I can't figure out how to round down to an exponent of 1.2

-fix-

Here's the resulting working version...

fitScale = function (width, height)
{
  var wScale = graph.element.offsetWidth / width,
      hScale = graph.element.offsetHeight / height,
      snugg = wScale < hScale ? wScale : hScale,
      exp = Math.log(snugg) / Math.log(1 / 1.2),
      scale = Math.pow(1 / 1.2, Math.ceil(exp));
  return 900 / scale;
}
È stato utile?

Soluzione

My math skills are rusty, so go easy if I wander off the Path of Truth here.

Basically you want to know what power y of 1.2 is equal to some given number x. While the log function would appear not to be helpful since it tells you what power of e will equal your number x, with some mad logarithm skillz you can in fact use that to get to where you want to go:

var y = Math.log(x) / Math.log(1.2);

Odds are pretty good that y won't be a whole number which is I think what you want, so if you just go ahead and Math.floor(y), you should be all set.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top