global.js 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. 'use strict';
  2. class Timer {
  3. constructor(callback, delay, paused) {
  4. this.callback = callback;
  5. this.timerId = undefined;
  6. this.start = undefined;
  7. this.paused = paused;
  8. this.remaining = delay * 1000;
  9. this.timeWhenPaused = 0;
  10. this.timePaused = Date.now();
  11. if (!paused) {
  12. this.resume();
  13. }
  14. }
  15. pause() {
  16. clearTimeout(this.timerId);
  17. this.remaining -= Date.now() - this.start;
  18. this.timePaused = Date.now();
  19. this.paused = true;
  20. }
  21. ifNotPaused() {
  22. if (!this.paused) {
  23. this.resume();
  24. }
  25. }
  26. resume() {
  27. this.start = Date.now();
  28. clearTimeout(this.timerId);
  29. this.timerId = setTimeout(this.callback, this.remaining);
  30. this.timeWhenPaused = Date.now() - this.timePaused;
  31. this.paused = false;
  32. }
  33. resetTimeWhenPaused() {
  34. this.timeWhenPaused = 0;
  35. }
  36. getTimePaused() {
  37. if (!this.paused) {
  38. return this.timeWhenPaused;
  39. } else {
  40. return Date.now() - this.timePaused;
  41. }
  42. }
  43. }
  44. function getRandomNumber(min, max) {
  45. return Math.floor(Math.random() * (max - min + 1)) + min;
  46. }
  47. module.exports = {
  48. io: null, // Socket.io
  49. db: null, // Database
  50. htmlEntities: str => {
  51. return String(str).replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/"/g, '&quot;');
  52. },
  53. getRandomNumber,
  54. generateRandomString: len => {
  55. let chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789".split("");
  56. let result = [];
  57. for (let i = 0; i < len; i++) {
  58. result.push(chars[getRandomNumber(0, chars.length - 1)]);
  59. }
  60. return result.join("");
  61. },
  62. getSocketFromId: function(socketId) {
  63. return this.io.sockets.sockets[socketId];
  64. },
  65. Timer
  66. };