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