Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Calculate percentage of completion from number X to Y

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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?

>Solution :

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>
  );
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading