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

How to round down number from array index ? similar to closet

I’m trying to solve the following example script;

player = {
        hp : 150,
        maxHp : 150,
        def : 12,
        isDead : false,
        level: 1,
        xp : 0,
        maxXp : [0,10,50,150,300,500,800,1500,3000,5000,9000,20000,50000,100000],
        update(){
            const thresholds = [0,10,50,150,300,500,800,1500,3000,5000,9000,20000,50000,100000];
            const index = thresholds.findIndex((t) => t > this.xp);
            const level = index === -1 ? thresholds.length : index;
            this.level = level
        }
}

In this case, I want to add a certain level to a player based on how much experience they have.
Therefore, I added 15x numbers in the array that the player needs to reach a certain level.
As an example, index 0 equals level 1 (default) and index 4 equals level 5.

If my XP is 299, then I’ll be level 5 because my method only gets closet numbers.

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

>Solution :

I think the easiest way is to find the index of which the required exp is greater than the total exp. Then you can check if the index was found or not for the level.

const thresholds = [0,10,50,150,300,500,800,1500,3000,5000,9000,20000,50000,100000];

const xp = 299;

const index = thresholds.findIndex((t) => t > xp);

const level = index === -1 ? thresholds.length : index;

console.log(level);
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