Fix computer moves randomness, rename random() into randInt()
[vchess.git] / client / src / utils / alea.js
CommitLineData
c66a829b
BA
1// Random (enough) string for socket and game IDs
2export function getRandString()
3{
4 return (Date.now().toString(36) + Math.random().toString(36).substr(2, 7))
5 .toUpperCase();
6}
7
656b1878 8export function randInt(min, max)
c66a829b
BA
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
19export 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 {
656b1878 25 const rand = randInt(index, arr.length);
c66a829b
BA
26 const temp = cpArr[index];
27 cpArr[index] = cpArr[rand];
28 cpArr[rand] = temp;
29 }
30 return cpArr.slice(0, n);
31}
32
33export function shuffle(arr)
34{
35 return sample(arr, arr.length);
36}