1function getRandomNumberBetween(min,max){
2 return Math.floor(Math.random()*(max-min+1)+min);
3}
4
5//usage example: getRandomNumberBetween(20,400);
6
1function getRandomInt(min, max) {
2 min = Math.ceil(min);
3 max = Math.floor(max);
4 return Math.floor(Math.random() * (max - min)) + min; //The maximum is exclusive and the minimum is inclusive
5}
6
1const randomNumber = ({ min, max } = { min: 0, max: 1 }) => {
2 if (min >= max) {
3 throw Error(
4 `minimum value (${min}) is larger than or equal to maximum value (${max})`
5 );
6 }
7
8 return Math.floor(Math.random() * Math.floor(max - min + 1) + min);
9};
10
11// Usage: random number between 10 and 100.
12const n = randomNumber({ min: 10, max: 100 });
1const range = (options) => {
2 const { from = 0, step = 1, to } = options;
3
4 if (!to) {
5 throw Error('"to" must be specified');
6 }
7
8 if (to <= from) {
9 throw Error(`"to (${to})" is lesser than or equal to "from (${from})"`);
10 }
11
12 return Array.from(
13 { length: Math.ceil((to - from) / step) },
14 (_, i) => i * step + from
15 );
16};
17
18// Usage
19const r1 = range({ to: 10 });
20// [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
21
22const r2 = range({ from: 10, to: 20 });
23// [10, 11, 12, 13, 14, 15, 16, 17, 18, 19]
24
25const r3 = range({ from: 10, to: 20, step: 3 });
26// [10, 13, 16, 19]