Skip to content

Instantly share code, notes, and snippets.

@zisra
Last active October 23, 2023 01:19
Show Gist options
  • Select an option

  • Save zisra/c3cbb281da4eda3e501c060b10e7bef7 to your computer and use it in GitHub Desktop.

Select an option

Save zisra/c3cbb281da4eda3e501c060b10e7bef7 to your computer and use it in GitHub Desktop.

Revisions

  1. zisra revised this gist Oct 23, 2023. No changes.
  2. zisra renamed this gist Oct 23, 2023. 1 changed file with 0 additions and 0 deletions.
    File renamed without changes.
  3. zisra created this gist Oct 23, 2023.
    59 changes: 59 additions & 0 deletions eloCalculator.js
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,59 @@
    const K_FACTOR = 20;
    const RATING_SCALING = 400;

    interface Player {
    isWin: boolean;
    elo: number;
    }

    interface Result {
    firstPlayer: Player;
    secondPlayer: Player;
    }

    function calculateElo({ firstPlayer, secondPlayer }: Result): [number, number] {
    const expectedOutcomeFirst = 1 / (1 + 10 ** ((secondPlayer.elo - firstPlayer.elo) / RATING_SCALING));
    const expectedOutcomeSecond = 1 - expectedOutcomeFirst;

    const actualOutcomeFirst = firstPlayer.isWin ? 1 : 0;
    const actualOutcomeSecond = secondPlayer.isWin ? 1 : 0;

    const newEloFirst = firstPlayer.elo + K_FACTOR * (actualOutcomeFirst - expectedOutcomeFirst);
    const newEloSecond = secondPlayer.elo + K_FACTOR * (actualOutcomeSecond - expectedOutcomeSecond);

    return [newEloFirst, newEloSecond];
    }

    function predictOutcome(firstPlayerElo: number, secondPlayerElo: number): [number, number] {
    const expectedOutcomeFirst = 1 / (1 + 10 ** ((secondPlayerElo - firstPlayerElo) / RATING_SCALING));
    const expectedOutcomeSecond = 1 - expectedOutcomeFirst;

    return [expectedOutcomeFirst, expectedOutcomeSecond];
    }

    async function main() {
    const firstPlayerScore = 1000
    const secondPlayerScore = 1026;

    const [newEloFirstPlayer, newEloSecondPlayer] = calculateElo({
    firstPlayer: {
    isWin: true,
    elo: firstPlayerScore,
    },
    secondPlayer: {
    isWin: false,
    elo: secondPlayerScore,
    },
    });

    console.log("Updated Elo Ratings:");
    console.log(`First Player: ${newEloFirstPlayer}`);
    console.log(`Second Player: ${newEloSecondPlayer}`);

    const [expectedOutcomeFirst, expectedOutcomeSecond] = predictOutcome(newEloFirstPlayer, newEloSecondPlayer);
    console.log("Expected Outcome:");
    console.log(`First Player: ${expectedOutcomeFirst}`);
    console.log(`Second Player: ${expectedOutcomeSecond}`);
    }

    main();