Skip to content

Instantly share code, notes, and snippets.

@Avi-E-Koenig
Created December 15, 2022 13:46
Show Gist options
  • Save Avi-E-Koenig/bfa3f59fb30f4ce581a7177722d10880 to your computer and use it in GitHub Desktop.
Save Avi-E-Koenig/bfa3f59fb30f4ce581a7177722d10880 to your computer and use it in GitHub Desktop.
Sort Balls by color and num
// take bag of balls in colors red,yellow,blue green with digit 1-9
// args array of balls
const ball = { color: 'red', num: 1 };
/**
*
* @param {number} min
* @param {number} max
* @returns
*/
function randomIntFromInterval(min, max) {
// min and max included
return Math.floor(Math.random() * (max - min + 1) + min);
}
function makeArr() {
return Array.from({ length: randomIntFromInterval(10, 50) }, (_, i) => {
const colors = ['red', 'yellow', 'blue', 'green'];
return {
color: colors[randomIntFromInterval(0, 3)],
num: randomIntFromInterval(1, 10),
};
});
}
/**
* @typedef {{color: string, num: number}} Ball
*
* @param {Ball[]} balls
* @return {Ball[]} balls
*/
function sortBalls(balls) {
const colMap = {
red: 1,
yellow: 2,
blue: 3,
green: 4,
};
return balls.sort((a, b) => colMap[a.color] - colMap[b.color] || a.num - b.num);
}
console.log('sortedBalls', sortBalls(makeArr()));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment