Skip to content

Instantly share code, notes, and snippets.

@dfabulich
Last active September 25, 2023 02:45
Show Gist options
  • Save dfabulich/fc6b13a8bffc5518c4731347de642749 to your computer and use it in GitHub Desktop.
Save dfabulich/fc6b13a8bffc5518c4731347de642749 to your computer and use it in GitHub Desktop.
Evan Miller Ranking Items with Star Ratings, in JavaScript
"use strict";
// based on unutbu's stackoverflow answer
// https://stackoverflow.com/a/40958702/54829
// which is based on Evan Miller's blog post
// http://www.evanmiller.org/ranking-items-with-star-ratings.html
function starsort(ratings) {
function sum(array) { return array.reduce((x, y) => x + y, 0) };
function square(x) { return x * x; };
const confidenceZ = 1.65;
// include five fake reviews
// 1 1-star, 1 2-star, 1 3-star, 1 4-star, 1 5-star
const fakeRatings = ratings.map(count => count + 1);
const N = sum(fakeRatings);
const average = sum(fakeRatings.map((count, i) => (i + 1) * count)) / N;
// Dirichlet standard deviation of average
const x = sum(fakeRatings.map((count, i) => square(i + 1) * count)) / N;
const standardDeviation = Math.sqrt((x - square(average)) / (N + 1));
return average - confidenceZ * standardDeviation;
}
console.log(starsort([60, 80, 75, 20, 25]));
@sambeau
Copy link

sambeau commented Sep 25, 2023

Here's a Go version, for anyone searching like I was:

// starsort.go

package main

import(
	"fmt"
	"math"
)

// 	http://www.evanmiller.org/ranking-items-with-star-ratings.html

func sum(ns []int) int {
	var total int
	for _,n := range ns {
		total += n
	}
	return total
}

func f(s []int, ns []int)float64{
	N := sum(ns)
	K := len(ns)
	ks := make([]int,K)
	for i:=0; i<5; i++ {
		ks[i] = s[i] * (ns[i]+1)
	}
	return float64(sum(ks)) / float64(N+K)
}

func starSort(ns []int) float64 {
	N := sum(ns)
	K := len(ns)
	s := []int{5, 4, 3, 2, 1}
	s2 := []int{25, 16, 9, 4, 1}
	z := float64(1.65)
	fsns := f(s, ns)
	return fsns - z * math.Sqrt(((f(s2, ns) - (fsns*fsns)) / float64(N+K+1)))
}

func main(){
	fmt.Println(starSort([]int{60, 80, 75, 20, 25}))
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment