Last active
May 30, 2020 15:39
-
-
Save jherax/602fb6e999e03e36233f95715d0891fb to your computer and use it in GitHub Desktop.
Generates an array of unique values given a range
This file contains 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
/** | |
* Returns a random integer between min and max | |
* | |
* @export | |
* @param {Number} min: minimum value (inclusive) | |
* @param {Number} max: maximum value (inclusive) | |
* @return {Number} | |
*/ | |
function randomInt(min, max) { | |
return Math.floor(Math.random() * (1 + max - min)) + min; | |
} | |
/** | |
* Generates unique numbers given a range. | |
* | |
* @private | |
* @param {Number} count: how many numbers will be generated | |
* @param {Number} min: minimum value (inclusive) | |
* @param {Number} max: maximum value (inclusive) | |
* @param {Array} array: the collection of unique numbers generated | |
*/ | |
function generator(count = 1, min = 1, max = 10, array) { | |
let value; | |
while (array.length < count) { | |
value = randomInt(min, max); | |
if (array.indexOf(value) === -1) { | |
array.push(value); | |
} | |
} | |
} | |
/** | |
* Generates an array of unique numbers given a range. | |
* | |
* @export | |
* @param {Number} count: how many numbers will be generated | |
* @param {Number} min: minimum positive value (inclusive) | |
* @param {Number} max: maximum positive value (inclusive) | |
* @return {Array} the collection of unique numbers generated | |
*/ | |
function randomNumbers(count, min, max) { | |
const uniqueNumbers = []; | |
if (count < 0 || min < 0 || max < 0) { | |
throw new Error('Parameters must be positive numbers'); | |
} | |
generator(count, min, max, uniqueNumbers); | |
return uniqueNumbers; | |
} |
This file contains 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
//generates 7 unique numbers between 60 and 100 | |
var range1 = randomNumbers(7, 60, 100); | |
//generates 5 unique numbers between 0 and 10 | |
var range2 = randomNumbers(5, 0, 10); | |
//no arguments | |
//generates 1 number between 1 and 10 | |
var number = randomNumbers()[0]; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment