Skip to content

Instantly share code, notes, and snippets.

@swingley
Created January 21, 2016 07:25
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save swingley/e922199a4c4e41d5b612 to your computer and use it in GitHub Desktop.
Save swingley/e922199a4c4e41d5b612 to your computer and use it in GitHub Desktop.
'use strict';
const fs = require('fs');
const sortBy = require('sort-by');
const scores = 'scores.json';
const out = 'scores-with-ranks.json';
const weeksFile = 'weeks-ranked.json';
const teamsFile = 'teams-ranked.json';
fs.readFile(scores, (err, data) => {
data = JSON.parse(data);
data.forEach((d, index) => {
// Add a property to keep track of rank from week-to-week.
// That property will also include a running total.
d.ranks = {};
for ( let i = 1; i < 18; i++ ) {
// Pull out scores up to this week, make them numbers.
let scores = d.scores.slice(0, i).map((s) => +s);
if ( scores.length > 1 ) {
// After week one, worst week is dropped.
let min = Math.min.apply(null, scores);
// Remove the lowest score.
scores.splice(scores.indexOf(min), 1);
}
let runningTotal = scores.reduce((a, b) => a + b);
d.ranks['w' + i] = { total: runningTotal, rank: 0 }
}
});
// Each team has a ranks object.
// Pull out the totals for each team for each week then sort.
let weeks = {};
for ( let i = 1; i < 18; i++ ) {
let week = 'w' + i;
weeks[week] = [];
data.forEach((d) => {
weeks[week].push({
name: d.name,
total: d.ranks[week].total
});
});
// Sort by rank.
weeks[week].sort(sortBy('-total'));
// Explicitly add rank as a property.
weeks[week].forEach((w, index) => w.position = index+1);
// Add the rank info to the data with weekly scores.
data.forEach((d) => {
weeks[week].forEach((w) => {
if ( w.name == d.name ) {
d.ranks[week].rank = w.position;
}
});
});
}
// Make another object where each team is a key and value is array of ranks.
let teams = {};
for ( let week in weeks ) {
let w = weeks[week];
w.forEach((t) => {
if ( !teams.hasOwnProperty(t.name) ) {
teams[t.name] = [];
}
teams[t.name].push(t.position);
});
}
fs.writeFile(teamsFile, JSON.stringify(teams, null, 2));
fs.writeFile(weeksFile, JSON.stringify(weeks, null, 2));
fs.writeFile(out, JSON.stringify(data, null, 2));
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment