Apply store pattern to track global app state
[vchess.git] / client / src / utils / alea.js
diff --git a/client/src/utils/alea.js b/client/src/utils/alea.js
new file mode 100644 (file)
index 0000000..337b25f
--- /dev/null
@@ -0,0 +1,36 @@
+// Random (enough) string for socket and game IDs
+export function getRandString()
+{
+  return (Date.now().toString(36) + Math.random().toString(36).substr(2, 7))
+    .toUpperCase();
+}
+
+export function random (min, max)
+{
+  if (!max)
+  {
+    max = min;
+    min = 0;
+  }
+  return Math.floor(Math.random() * (max - min) ) + min;
+}
+
+// Inspired by https://github.com/jashkenas/underscore/blob/master/underscore.js
+export function sample (arr, n)
+{
+  n = n || 1;
+  let cpArr = arr.map(e => e);
+  for (let index = 0; index < n; index++)
+  {
+    const rand = getRandInt(index, n);
+    const temp = cpArr[index];
+    cpArr[index] = cpArr[rand];
+    cpArr[rand] = temp;
+  }
+  return cpArr.slice(0, n);
+}
+
+export function shuffle(arr)
+{
+  return sample(arr, arr.length);
+}