EN
TypeScript - random int in range
0 points
Hello, today I would like to show you how to generate random integer number in the given range in TypeScript.
xxxxxxxxxx
1
/*
2
inclusive min (result can be equal to min value)
3
inclusive max (result can be equal to max value)
4
*/
5
6
const randomizeInteger = (min: number, max: number): number => {
7
return min + Math.floor((max - min + 1) * Math.random());
8
};
9
10
11
// Usage example:
12
13
console.log(randomizeInteger(0, 2)); // 0
14
console.log(randomizeInteger(0, 2)); // 2
15
console.log(randomizeInteger(0, 2)); // 1
16
console.log(randomizeInteger(0, 2)); // 1
Example output:
xxxxxxxxxx
1
0
2
2
3
1
4
1
If we want to change the range, we just need to call this method with our desired min and max.
About min and max value as stated in a comment:
- inclusive min (result can be equal to min value)
- inclusive max (result can be equal to min value)