api/src/lib/plexus.ts

49 lines · 1393 bytes

4 symbols in this file
 1/**
 2 * Aggregates Plexus crowdsourced ratings into de-Googled compatibility status.
 3 * Each rating scores an app out of 4, native is no-microG and micro_g is with it.
 4 * Scores map to gold (flawless), silver, bronze (limited) and broken.
 5 */
 6
 7export interface PlexusRating {
 8  rating_type?: string
 9  score?: { numerator?: number; denominator?: number }
10}
11
12const statusFor = (ratio: number) =>
13  ratio >= 0.875
14    ? 'gold'
15    : ratio >= 0.625
16      ? 'silver'
17      : ratio >= 0.375
18        ? 'bronze'
19        : 'broken'
20
21// Mean the matching scores into a status summary, or mark the type unavailable
22const summarize = (ratings: PlexusRating[], type: string) => {
23  const ratios: number[] = []
24  for (const r of ratings) {
25    const num = r.score?.numerator
26    const den = r.score?.denominator
27    if (
28      r.rating_type === type &&
29      typeof num === 'number' &&
30      typeof den === 'number' &&
31      den > 0
32    ) {
33      ratios.push(num / den)
34    }
35  }
36  if (ratios.length === 0) return { available: false as const }
37  const ratio = ratios.reduce((sum, x) => sum + x, 0) / ratios.length
38  return {
39    available: true as const,
40    status: statusFor(ratio),
41    score: Math.round(ratio * 40) / 10,
42    ratings: ratios.length,
43  }
44}
45
46export const summarizeRatings = (ratings: PlexusRating[]) => ({
47  native: summarize(ratings, 'native'),
48  microg: summarize(ratings, 'micro_g'),
49})