Last active
December 13, 2016 16:09
-
-
Save Anthodpnt/631d82019abe06470896d7eedd828785 to your computer and use it in GitHub Desktop.
Math - Random Integer
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
/** | |
* This gist is for Javascript beginners. | |
* @author: Anthony Du Pont <[email protected]> | |
* @site: https://www.twitter.com/JsGists | |
* | |
* The `Math.random()` method only return a random number between 0 and 1. | |
* But what if you want a larger range than [0, 1] ? We need to improve this | |
* random method. | |
* | |
* Example: | |
* I want to get a random number from the range [10, 20] inclusive which means that 10 or 20 can come out. | |
* | |
* Note: This random function works with negative and/or positive range ([0, 10], [-10, 5], [-20, -10]). | |
**/ | |
const number = randomInteger(10, 20); // Return a random number between 10 and 20 (10, 5, 7, 3, 20, 17, ...) | |
function randomInteger(min, max) { | |
return Math.floor(Math.random() * (max - min + 1)) + min; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment