-
Notifications
You must be signed in to change notification settings - Fork 1
/
random.js
58 lines (47 loc) · 1.36 KB
/
random.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
export {
randomPositiveInt,
randomInt,
randomFloat,
randomShuffle,
};
/**
Returns a random integer between 0 (included) and
maxExlusive (excluded)
@param {uint} maxExclusive
@return {uint} random positive integer
*/
const randomPositiveInt = function (maxExclusive = 2) {
return Math.floor(Math.random() * maxExclusive);
};
/**
Returns a random integer between minInclusive (included) and
maxExlusive (excluded)
@param {int} maxExclusive
@param {int} maxExclusive
@return {int} random integer
*/
const randomInt = function (minInclusive = 0, maxExclusive = 2) {
return minInclusive + randomPositiveInt(maxExclusive - minInclusive);
};
/**
Returns a random number between minInclusive (included) and
maxExlusive (excluded)
@param {number} maxExclusive
@param {number} maxExclusive
@return {number} random number
*/
const randomFloat = function (minInclusive = 0, maxExclusive = 1) {
return minInclusive + (Math.random() * (maxExclusive - minInclusive));
};
const randomShuffle = (array) => {
const indexes = Array.from(array, (value, index) => {
return index;
});
const shuffledArray = [];
while (shuffledArray.length < array.length) {
const randomIndex = randomInt(0, indexes.length);
shuffledArray.push(array[indexes[randomIndex]]);
indexes.splice(randomIndex, 1);
}
return shuffledArray;
};