JSFiddle - React, Tailwind, and code Playground
HTML
<div id="log"></div>
JavaScript
// Implement checkAndAddHighScore() where you have a list that keeps the top 5 high scores
var highScores = [];
function checkAndAddHighScore(score) {
// Check if `score` is a high score
// If it is, store it in the `highScore` list
// Allow no more than 5 high scores in the list at a time
if (highScores.length < 5) {
highScores.push(score); //not sure how to put score in the correct position
highScores.sort();
}
else {
rem = getMin(highScores);
if (score > rem)
highScores.remove(rem);
highScores.push(score);
highScores.sort();
}
log(highScores);
}
function getMin(scores) {
var min = scores[0];
for (var i = 1; i < scores.length; i++) {
if (scores[i] < min)
min = scores[i]
}
return min;
}
/*
score: 100
highScores = [50, 40, 30, 20, 10]
after, highScores = [100, 50, 40, 30, 20]
*/
Array.prototype.remove = function(item) {
var i = this.indexOf(item);
if (i === undefined || i < 0) {
return undefined;
}
return this.splice(i, 1);
};
function log(message) {
var p = document.createElement('p');
var d = document.getElementById('log');
p.textContent = message;
d.insertBefore(p, d.firstChild);
}
log(checkAndAddHighScore(100));
log(checkAndAddHighScore(100));
log(checkAndAddHighScore(100));
log(checkAndAddHighScore(100));
log(checkAndAddHighScore(100));
log(checkAndAddHighScore(200));
log(checkAndAddHighScore(300));
log(checkAndAddHighScore(400));