Commit | Line | Data |
---|---|---|
98db2082 BA |
1 | export const util = |
2 | { | |
3 | // Source: https://www.quirksmode.org/js/cookies.html | |
4 | setCookie: function(name, value) | |
5 | { | |
6 | var date = new Date(); | |
7 | date.setTime(date.getTime()+(183*24*60*60*1000)); //6 months | |
8 | var expires = "; expires="+date.toGMTString(); | |
9 | document.cookie = name+"="+value+expires+"; path=/"; | |
10 | }, | |
11 | ||
12 | getCookie: function(name, defaut) { | |
13 | var nameEQ = name + "="; | |
14 | var ca = document.cookie.split(';'); | |
15 | for (var i=0;i < ca.length;i++) | |
16 | { | |
17 | var c = ca[i]; | |
18 | while (c.charAt(0)==' ') | |
19 | c = c.substring(1,c.length); | |
20 | if (c.indexOf(nameEQ) == 0) | |
21 | return c.substring(nameEQ.length,c.length); | |
22 | } | |
23 | return defaut; //cookie not found | |
24 | }, | |
25 | ||
8d61fc4a BA |
26 | random: function(min, max) |
27 | { | |
28 | if (!max) | |
29 | { | |
30 | max = min; | |
31 | min = 0; | |
32 | } | |
33 | return Math.floor(Math.random() * (max - min) ) + min; | |
34 | }, | |
35 | ||
36 | // Inspired by https://github.com/jashkenas/underscore/blob/master/underscore.js | |
37 | sample: function(arr, n) | |
38 | { | |
39 | n = n || 1; | |
40 | let cpArr = arr.map(e => e); | |
41 | for (let index = 0; index < n; index++) | |
42 | { | |
43 | const rand = getRandInt(index, n); | |
44 | const temp = cpArr[index]; | |
45 | cpArr[index] = cpArr[rand]; | |
46 | cpArr[rand] = temp; | |
47 | } | |
48 | return cpArr.slice(0, n); | |
49 | }, | |
50 | ||
51 | shuffle: function(arr) | |
52 | { | |
53 | return sample(arr, arr.length); | |
54 | }, | |
55 | ||
56 | range: function(max) | |
57 | { | |
58 | return [...Array(max).keys()]; | |
59 | } | |
60 | ||
61 | // TODO: rename into "cookie" et supprimer les deux ci-dessous | |
98db2082 BA |
62 | // Random (enough) string for socket and game IDs |
63 | getRandString: function() | |
64 | { | |
65 | return (Date.now().toString(36) + Math.random().toString(36).substr(2, 7)) | |
66 | .toUpperCase(); | |
67 | }, | |
68 | ||
69 | // Shortcut for an often used click (on a modal) | |
70 | doClick: function(elemId) | |
71 | { | |
72 | document.getElementById(elemId).click(); //or ".checked = true" | |
73 | }, | |
98db2082 | 74 | }; |