Home > Enterprise >  Formula to squash big numbers but keep smaller numbers in range 1 to 100
Formula to squash big numbers but keep smaller numbers in range 1 to 100

Time:06-19

I show a chip as a div in the DOM.

If I have 1 chip, I have 1 div, 2 chips, 2 div, 3 chips, 3 div, 4 chips, 3 div.

As this can get high numbers quickly with many chips with different colors for 9 players each, I want a function to limit this number to sensible values, while retaining the visual indication of amount of chips.

// Map range 1-100 to 1-20 in a super exponential fashion so smaller chips don't get any smaller, but big numbers get trimmed down.
function m_n_chips(actual_chips: number) {
  if (actual_chips < 4) { return actual_chips }

  // what else do I need here
}

CodePudding user response:

The described behavior reminds me of a root function. it doesn't affect numbers that are small but the larger numbers we insert into the function, the more it gets squashed down.

You can vary the "factor of squashing" by multiplying x with a coefficient

Alternatively, you can use a logarithmic function which is the reverse of an exponential. This results in an even greater squashing effect

function m_n_chips(actual_chips: number) {
  if (actual_chips < 4) { return actual_chips }

  result = Math.sqrt(4 * x);
  // other option: use logarithm
  // result = Math.log(x) / Math.log(4);

  return Math.round(result);
}

When returning we convert the result to the nearest integer.

Hope that helps!

(Btw: For the future please provide more information e.g language, project details and how you came to your question)

  • Related