DEV Community

Cover image for Rating Algorithm + Example written in JS, PHP, and Go
Brama Udi
Brama Udi

Posted on • Updated on

Rating Algorithm + Example written in JS, PHP, and Go

As we know Rating are used to make a feedback between developer and user or something similar, i thinks that was the best way to ask people about how the feel do you experience when using the product, it's simple and easy to understand for both devs & user.

Math

The logic behind rating system is quite simple as this:

rating = quantity / sum total
Enter fullscreen mode Exit fullscreen mode

For more explanation i have create some condition to simulate the rating usage in real life;

Example: There is a guy who sell a fried rice, he want to ask his customer about the food taste, he take a survey for 10 of his customer to rate between 1 to 5 point.

Then the result is:

4 3 3 4 2 5 2 3 5 1 
Enter fullscreen mode Exit fullscreen mode

Then we can get the rating result by counting like this;

A = 4 + 3 + 3 + 4 + 2 + 5 + 2 + 3 + 5 + 1
B = 10
rating = A / B
Enter fullscreen mode Exit fullscreen mode

Explain: A is addition of each rate quantity, so in this case A will have value 32 while B is a rate quantity itself then the value is 10, and rating value are the result of divided value of A and B which is give a result 3.2.

Just Show Me The Code

Ok, don't waste your time by reading my ~shit~ explanation while you're getting more understand with just reading the code. :)

JavaScript:

const rates = [4, 3, 3, 4, 2, 5, 2, 3, 5, 1]

let total = 0
rates.forEach(data => {
  total += data
})

const qty = rates.length
const rating = total / qty

console.log("Rating Result:", rating) // Rating Result: 3.2
Enter fullscreen mode Exit fullscreen mode

PHP:

$rates = array(4, 3, 3, 4, 2, 5, 2, 3, 5, 1);

$total = 0;
foreach ($rates as $data) {
  $total += $data;
}

$qty = count($rates);
$rating = $total / $qty;

echo 'Rating Result: ' . $rating; // Rating Result: 3.2
Enter fullscreen mode Exit fullscreen mode

Go:

package main

import "fmt"

var rates = []int{4, 3, 3, 4, 2, 5, 2, 3, 5, 1}

func main() {

    var total int = 0
    for _, data := range rates {
        total += data
    }

    var qty int = len(rates)

    // The function float64() is needed
    // to convert decimal number of result 
    var rating float64 = float64(total) / float64(qty)

    fmt.Printf("Rating Result: %.1f\n", rating) // Rating Result: 3.2
}
Enter fullscreen mode Exit fullscreen mode

Top comments (0)