Created
December 15, 2022 13:46
-
-
Save Avi-E-Koenig/bfa3f59fb30f4ce581a7177722d10880 to your computer and use it in GitHub Desktop.
Sort Balls by color and num
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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