Created
April 30, 2020 19:10
-
-
Save midknightmare666/2d8b181afc3ed86b4b5e789e73d7bd76 to your computer and use it in GitHub Desktop.
Generate A Random Number Withing A Range But Exclude A Subset Of Numbers
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
/** | |
* @function randomInt | |
* @description Generate A Random Number Withing A Range But Exclude A Subset Of Numbers | |
* | |
* @param {Number} min Minumum Number | |
* @param {Number} max Maximum Number | |
* @param {Array<Number>} exclude Array Of Numbers To Exclude | |
* @returns {Number} | |
* @example randomInt(2, 10, [3, 5, 7]) | |
*/ | |
const randomInt = (min, max, exclude) => { | |
if ([min, max].forEach(p => p.constructor !== Number)) return new TypeError('Paramater(s) Must Be A Number Type'); | |
if (exclude.constructor !== Array) return new TypeError('Parameter Must Be An Array Of Number(s)'); | |
const nums = []; | |
const excludeNums = new Set(exclude); | |
for (let i = min; i <= max; i++) { | |
if (!excludeNums.has(i)) nums.push(i); | |
}; | |
if (nums.length === 0) return false; | |
const index = Math.floor(Math.random() * nums.length); | |
return nums[index]; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment