Show percentile for character rankings

This commit is contained in:
Eduard Urbach 2018-10-29 19:52:25 +09:00
parent ad467398ef
commit a9abcf0efb
2 changed files with 20 additions and 6 deletions

View File

@ -2,7 +2,6 @@ package character
import (
"net/http"
"strconv"
"github.com/aerogo/aero"
"github.com/animenotifier/arn"
@ -18,11 +17,21 @@ func Ranking(ctx *aero.Context) string {
return ctx.Error(http.StatusNotFound, "Character not found", err)
}
// Create response object
response := struct {
Rank int `json:"rank"`
Percentile float64 `json:"percentile"`
}{}
// Sort characters
characters := arn.FilterCharacters(func(character *arn.Character) bool {
return !character.IsDraft
})
if len(characters) == 0 {
return ctx.JSON(response)
}
arn.SortCharactersByLikes(characters)
// Allow CORS
@ -31,11 +40,13 @@ func Ranking(ctx *aero.Context) string {
// Return ranking
for index, character := range characters {
if character.ID == id {
return strconv.Itoa(index + 1)
response.Rank = index + 1
response.Percentile = float64(response.Rank) / float64(len(characters))
return ctx.JSON(response)
}
}
// If the ID wasn't found for some reason,
// return an empty string.
return ""
return ctx.JSON(response)
}

View File

@ -450,14 +450,17 @@ export default class AnimeNotifier {
for(let element of findAll("character-ranking")) {
fetch(`/api/character/${element.dataset.characterId}/ranking`).then(async response => {
let ranking = await response.text()
let ranking = await response.json()
if(ranking.length === 0) {
if(!ranking.rank) {
return
}
Diff.mutations.queue(() => {
element.textContent = "#" + ranking
let percentile = Math.ceil(ranking.percentile * 100)
element.textContent = "#" + ranking.rank.toString()
element.title = "Top " + percentile + "%"
})
})
}