/*
Description
You've been given the task of retrieving the top N high scores from players of a video game.
You need to write the function top_scores(records, n_top)
where records is a list of lists in the form of
records = [
["Bob", 100],
["Jane", 120],
["Alice", 10],
["Bob", 110],
["Bob", 10]
]
and n_top is an integer.
The function should return the top n records, where each user name can appear at most a single time. Records should be in from highest to lowest. Users with the same score should be in alphabetical order.
>>> top_scores(records, 3)
[["Jane", 120],["Bob", 110],["Alice", 10]]
if n_top is negative or 0, the returned value should be an empty list.
if n_top is greater than the total number of records, you should include as many valid records as possible.
*/
const records = [
["Bob", 100],
["Jane", 120],
["Alice", 10],
["Bob", 110],
["Bob", 10],
["Machin", 140]
];
const sort = fn => arr => arr.sort(fn);
const getScoreFromEntries = ([key, value]) => value;
const entriesByScore = (prev, next) => getScoreFromEntries(next) > getScoreFromEntries(prev)
const sortByScore = sort(entriesByScore);
const getMaxScoresObjectInEntries = (scores) => scores.reduce(
(result, [key, value]) => ({
...result,
[key]: Math.max(result[key] || 0, value)
}),
{}
)
const entriesFromObject = obj => Object.entries(obj);
const getMaxScoresInEntries = scores => entriesFromObject(getMaxScoresObjectInEntries(scores));
const slice = (start) => (stop) => (arr) => arr.slice(start, stop);
const positiveOrZero = (int) => int > 0
? int
: 0;
const getTop = (topLength) => slice(0)(positiveOrZero(topLength));
const topScores = (scores, topLength) => {
return getTop(topLength)(
sortByScore(
getMaxScoresInEntries(scores)
)
)
}
console.log(topScores(records, 5));
console.log(topScores(records, 3));
console.log(topScores(records, 0));
console.log(topScores(records, -3));