mercredi 15 janvier 2020

Shortenting a function (switch, if...else if, tertary syntax)

I have created a function that calculates a multiplier. Then I tried to shorten it a bit and two other version were produced.

function multiplier(p)
{
    switch(true)
    {
        case (p>=1&&p<=5):
            return 3-0.25*p;
        case (p>=6&&p<=10):
            return 2.25-0.125*p;
        case (p>=11&&p<=20):
            return 0.875;
        case (p>=21&&p<=30):
            return 0.75;
        case (p>=31&&p<=50):
            return 0.5;
        case (p>=51):
            return 0;
    }
}
function multiplier(p)
{
    if(p>=1&&p<=5){return 3-0.25*p;}
    else if(p>=6&&p<=10){return 2.25-0.125*p;}
    else if(p>=11&&p<=20){return 0.875;}
    else if(p>=21&&p<=30){return 0.75;}
    else if(p>=31&&p<=50){return 0.5;}
    else if(p>=51){return 0;}
}
function multiplier(p)
{
    p = Math.abs(p);
    return p>=1&&p<=5?3-0.25*p:(p>=6&&p<=10?2.25-0.125*p:(p>=11&&p<=20?0.875:(p>=21&&p<=30?0.75:(p>=31&&p<=50?0.5:0))));
}

My question is if there is another version (shorter) that I have missed?

Aucun commentaire:

Enregistrer un commentaire