9ff11593586a0a099d64f95ba919a91dfb4236ec
[vchess.git] / client / src / utils / alea.js
1 // Random (enough) string for socket and game IDs
2 export function getRandString() {
3 return (
4 Date.now().toString(36) +
5 Math.random()
6 .toString(36)
7 .substr(2, 7)
8 ).toUpperCase();
9 }
10
11 export function randInt(min, max) {
12 if (!max) {
13 max = min;
14 min = 0;
15 }
16 return Math.floor(Math.random() * (max - min)) + min;
17 }
18
19 // Inspired by https://github.com/jashkenas/underscore/blob/master/underscore.js
20 export function sample(arr, n) {
21 n = n || 1;
22 let cpArr = arr.map(e => e);
23 for (let index = 0; index < n; index++) {
24 const rand = randInt(index, arr.length);
25 const temp = cpArr[index];
26 cpArr[index] = cpArr[rand];
27 cpArr[rand] = temp;
28 }
29 return cpArr.slice(0, n);
30 }
31
32 export function shuffle(arr) {
33 return sample(arr, arr.length);
34 }