puzzle/common/Util.js

57 lines
1.2 KiB
JavaScript
Raw Normal View History

2020-11-08 14:49:34 +01:00
// get a unique id
export const uniqId = () => Date.now().toString(36) + Math.random().toString(36).substring(2)
2020-11-07 11:35:29 +01:00
// get a random int between min and max (inclusive)
export const randomInt = (min, max) => Math.floor(Math.random() * (max - min + 1)) + min
// get one random item from the given array
export const choice = (array) => array[randomInt(0, array.length - 1)]
export const throttle = (fn, delay) => {
let canCall = true
return (...args) => {
if (canCall) {
fn.apply(null, args)
canCall = false
setTimeout(() => {
canCall = true
}, delay)
}
}
}
2020-11-07 11:35:29 +01:00
// return a shuffled (shallow) copy of the given array
export const shuffle = (array) => {
let arr = array.slice()
for (let i = 0; i <= arr.length - 2; i++)
{
const j = randomInt(i, arr.length -1);
const tmp = arr[i];
arr[i] = arr[j];
arr[j] = tmp;
}
return arr
}
2020-11-25 22:03:35 +01:00
export const timestamp = () => {
const d = new Date();
return Date.UTC(
d.getUTCFullYear(),
d.getUTCMonth(),
d.getUTCDate(),
d.getUTCHours(),
d.getUTCMinutes(),
d.getUTCSeconds(),
d.getUTCMilliseconds(),
)
}
2020-11-07 11:35:29 +01:00
export default {
2020-11-08 14:49:34 +01:00
uniqId,
randomInt,
choice,
throttle,
2020-11-08 14:49:34 +01:00
shuffle,
2020-11-25 22:03:35 +01:00
timestamp,
2020-11-08 12:56:54 +01:00
}