UNPKG

elo-rating

Version:

elo-rating.js is a simple utility to calculate elo ratings for Node.js

59 lines (50 loc) 2.22 kB
"use strict"; // https://en.wikipedia.org/wiki/Elo_rating_system var EloRating = { /** * Calculates the difference between two ratings. * The difference is capped at +400 and -400. * @param {number} playerRating Rating of player one. * @param {number} opponentRating Rating of player two. * @return Difference between playerRating and opponentRating. */ ratingDifference: function ratingDifference(playerRating, opponentRating) { return Math.max(Math.min(playerRating - opponentRating, 400), -400); }, /** * Calculates the expected outcome of a game between two players of the * ratings playerRating and opponentRating. * * Formular: E = 1 / 1 + 10^((OR - PR)/400) * E: Expected value * PR: Player Rating * OR: Opponent Rating * * @param {number} playerRating Rating of player one. * @param {number} opponentRating Rating of player two. * @return The expected outcome for player one. */ expected: function expected(playerRating, opponentRating) { return 1 / (1 + Math.pow(10, this.ratingDifference(opponentRating, playerRating) / 400)); }, /** * Calculates the new ratings based on the given ratings and a flag * indicating if player one has won. * @param {number} playerRating Rating of player one. * @param {number} opponentRating Rating of player two. * @param {bool} playerWin Flag indicating if player one has won. * @param {number} k K Factor. By default 20. * @return New rating of the player and his opponent. */ calculate: function calculate(playerRating, opponentRating) { var playerWin = arguments.length <= 2 || arguments[2] === undefined ? true : arguments[2]; var k = arguments.length <= 3 || arguments[3] === undefined ? 20 : arguments[3]; var playerExpected = this.expected(playerRating, opponentRating); var ratingChange = parseInt(k * (!!playerWin - playerExpected), 10); return { playerRating: playerRating + ratingChange, opponentRating: opponentRating + ratingChange * -1 }; } }; module.exports = EloRating;