leaderboard
by jacobwsmith
JavaScript
// scores
const playerscores = [
{id: 5, roundscores: [1, 1, 1, 0]},
{id: 2, roundscores: [-2, -1, -1, -1]},
{id: 6, roundscores: null},
{id: 3, roundscores: [0, 0, -2, -1]},
{id: 4, roundscores: [0, 0, -1, -1]},
{id: 1, roundscores: [1, 0, -2, -1]},
];
const playernames = [
{id: 4, name: "Bob"},
{id: 5, name: "Ann"},
{id: 1, name: "Joe"},
{id: 2, name: "Sue"},
{id: 3, name: "Jane"},
{id: 6, name: "Larry"},
];
// Take home problem:
// Using the example dataset above
// write a method
// that accepts the collection of names and the collection of scores and returns a Leaderboard
// Leaderboard is a collection of {id: number, name: string, score: number, winner: boolean}
// where
// - total is the sum of round scores
// - sort by total least to greatest
// - assign winner boolean
// - does not include scores of null
const getLeaderboard = (playernames, playerscores) => {
const nameHash = playernames.reduce((acc, cur) => {
acc[cur.id] = cur.name;
return acc;
}, {});
return playerscores
.filter(item => item.roundscores)
.map(item => {
return {
id: item.id,
name: nameHash[item.id],
score: item.roundscores.reduce((acc, cur) => acc + cur),
winner: 'TODO'
}
}).sort((a, b) => {
// a is less than b by some ordering criterion
if (a.score < b.score) {
return -1;
}
// a is greater than b by the ordering criterion
if (a.score > b.score) {
return 1;
}
// a must be equal to b
return 0;
})
}
const result = getLeaderboard(playernames, playerscores);
console.log(result);