From b8695263ee05a29dbdeabdba244432d9b6397a3b Mon Sep 17 00:00:00 2001 From: Talasan Nicholson Date: Wed, 30 May 2018 11:07:10 -0500 Subject: [PATCH] ELO snippet formatting + performance Not assigning `arr.length` to a variable in a for loop means that the read is done on every iteration. --- snippets/elo.md | 17 ++++++++++------- 1 file changed, 10 insertions(+), 7 deletions(-) diff --git a/snippets/elo.md b/snippets/elo.md index 622cdc981..6e36ad874 100644 --- a/snippets/elo.md +++ b/snippets/elo.md @@ -15,17 +15,20 @@ const elo = ([...ratings], kFactor = 32, selfRating) => { const expectedScore = (self, opponent) => 1 / (1 + 10 ** ((opponent - self) / 400)); const newRating = (rating, i) => (selfRating || rating) + kFactor * (i - expectedScore(i ? a : b, i ? b : a)); + if (ratings.length === 2) { return [newRating(a, 1), newRating(b, 0)]; - } else { - for (let i = 0; i < ratings.length; i++) { - let j = i; - while (j < ratings.length - 1) { - [ratings[i], ratings[j + 1]] = elo([ratings[i], ratings[j + 1]], kFactor); - j++; - } + } + + for (let i = 0, l = ratings.length; i < l; i++) { + let j = i; + + while (j < l - 1) { + [ratings[i], ratings[j + 1]] = elo([ratings[i], ratings[j + 1]], kFactor); + j++; } } + return ratings; }; ```