Search code examples
javascriptrating-system

Javascript - Calculate missing 5 stars to reach desired rating


I would like to make a script that calculate how many "5" I need to reach 4.95 rating.

I created an object:

var obMed = {
   5: 0,
   4: 0,
   3: 0,
   2: 0,
   1: 0
 };

I got this function to update previous object with my rating

function upOB(a,b,c,d,e) {
    obMed["5"] = a;
    obMed["4"] = b;
    obMed["3"] = c;
    obMed["2"] = d;
    obMed["1"] = e;
    return obMed;
}

And this function to get the rating value

function med(obj) {
    div = obj["5"] + obj["4"] + obj["3"] + obj["2"] + obj["1"];
    somma = (obj["5"] * 5) + (obj["4"] * 4) + (obj["3"] * 3) + (obj["2"] * 2) + (obj["1"] * 1);
    media = (somma/div).toFixed(2);
    return media;
} 

At this point I would like to add 1 to object["5"] until my average is greater than or equal to 4.95 but I'm really stuck.

I tried loops with no results, probably I wrote them bad.


Solution

  • If you do the equations you get the following relation (using the same variable names that your code uses)

    function getNeed(div, somma) {
      return Math.ceil((4.95*div - somma) / 0.05);
    }
    

    As I understand that div is the total amount of votes sent, and somma is the sum of all scores.


    Math behind the method

    current score: somma / div
    if you add N votes of 5 stars, the new score would be: (somma + N * 5) / (div + N)
    If you want that to be equal to 4.95, then you do (somma + N * 5) / (div + N) = 4.95, and the result is that:
    N = (4.95*div - somma) / 0.05

    Then you'll have to ceil that value as @dvsoukup commented, as you cannot have a non-integer amount of votes. This way, for example, you would have as a result 7 if the value of the computed N was 6.72.