I'm doing this challenge to assign dense rankings to a player's score compared to a leadingboard. My following code works, but takes too long to run (some tests on the site fail on timeout error).
I'm wondering what else can I optimize? Any ideas?
function climbingLeaderboard(scores, alice) {
const reducedScores = getReducedScores(scores)
let lastIdxHit = reducedScores.length - 1
return alice.map((a) => {
for (let i = lastIdxHit; i >= 0; i--) {
const rs = reducedScores[i]
if (a < rs.value) {
return rs.rank + 1
}
lastIdxHit = i - 1
}
return 1
})
}
function getReducedScores(scores) {
let rank = 0
return scores.reduce((acc, s) => {
if (last(acc) && last(acc).value === s) {
return acc
}
rank++
return acc.concat({ value: s, rank })
}, [])
}
function last(arr) {
return arr[arr.length - 1]
}