Home > Blockchain >  Calculate percentage of completion from number X to Y
Calculate percentage of completion from number X to Y

Time:11-26

i'm stucked with a logic question.

i've created an app that setup an automatic badge when a user reach a certain number of post into a forum.

What i want to do is to fill the background of the badge with the percentage until next badge will be earned.

my code:

if (userPosts >= 5 && userPosts <= 10 ) {
        let bgPerc = 'background: -webkit-linear-gradient(left, #efe3af 25%,#ffffff 25%);'
        vnode.children.push(
              <span className="auto-badge" style={bgPerc}>
                <i class={tierOne} />
              'First Badge Text'
              </span>
        );

as you can see i want to change dinamically the background with the percentage of completion between 5 and 10

how can i do this with javascript?

CodePudding user response:

It's a linear function f(userPosts) = (userPosts - lowerBound) / (upperBound - lowerBound), in your example f(userPosts) = (userPosts - 5) / (10 - 5):

const lowerBound = 5;
const upperBound = 10;
if (userPosts >= lowerBound && userPosts <= upperBound ) {
  const perc = Math.ceil((userPosts - lowerBound) / (upperBound - lowerBound) * 100);
  let bgPerc = `background: -webkit-linear-gradient(left, #efe3af ${perc}%,#ffffff ${perc}%);`
  vnode.children.push(
    <span className="auto-badge" style={bgPerc}>
      <i class={tierOne} />
        'First Badge Text'
    </span>
  );
  • Related