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