Skip to content

A games launcher for GOG, Amazon and Epic Games for Linux, Windows and macOS.

1.7 KB
Raw Blame
interface TitleCandidate {
  name: string
}

const EDITION_SUFFIX =
  /^(the )?(game of the year|goty|definitive|deluxe|ultimate|complete|enhanced|remastered|remaster|anniversary|gold|special|collectors?|digital deluxe|directors cut|final cut|legendary|premium|extended|redux)\b/

const YEAR_SUFFIX = /^\d{4}\b/

export function normalizeTitle(title: string): string {
  return title
    .normalize('NFD')
    .replace(/[\u0300-\u036f]/g, '')
    .toLowerCase()
    .replaceAll('&', ' and ')
    .replace(/[™®©]/g, '')
    .replace(/[^a-z0-9]+/g, ' ')
    .trim()
}

/**
 * Picks the candidate that matches a game title, or nothing.
 *
 * Search results are fuzzy, so we only accept an exact normalized match or a
 * title that is the requested one plus an edition marker ("Definitive Edition",
 * "GOTY", "(2020)", …). Anything else is a different game as far as we are
 * concerned: showing the score or the screenshots of "GRIME II" on "GRIME"
 * would be worse than showing none.
 */
export function pickBestTitleMatch<T extends TitleCandidate>(
  candidates: T[],
  title: string
): T | undefined {
  const wanted = normalizeTitle(title)
  if (!wanted) {
    return undefined
  }

  const normalized = candidates.map((candidate) => ({
    candidate,
    normalized: normalizeTitle(candidate.name)
  }))

  const exact = normalized.find((entry) => entry.normalized === wanted)
  if (exact) {
    return exact.candidate
  }

  const edition = normalized.find((entry) => {
    if (!entry.normalized.startsWith(`${wanted} `)) {
      return false
    }

    const remainder = entry.normalized.slice(wanted.length).trim()
    return EDITION_SUFFIX.test(remainder) || YEAR_SUFFIX.test(remainder)
  })

  return edition?.candidate
}