Advertisement
Guest User

Untitled

a guest
Feb 21st, 2017
83
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.81 KB | None | 0 0
  1. const lines = {};
  2. const lineThrottles = {};
  3. const lastRun = {};
  4.  
  5. const nowServing = {
  6.  
  7. openLine(lineName, throttle = 0) {
  8. this.flushLine(lineName);
  9. lineThrottles[lineName] = throttle;
  10. },
  11.  
  12. flushLine(lineName) {
  13. lines[lineName] = [];
  14. lastRun[lineName] = 0;
  15. },
  16.  
  17. takeNumber(lineName, collapsible) {
  18.  
  19. if (!lines[lineName]) {
  20. this.openLine(lineName);
  21. }
  22.  
  23. const reservation = new Promise(resolve => {
  24. lines[lineName].push({resolve, collapsible});
  25. });
  26.  
  27. }
  28.  
  29. };
  30.  
  31. function now() {
  32. return (new Date()).valueOf()
  33. }
  34.  
  35. function lineLength(lineName) {
  36. return lines[lineName] ? lines[lineName].length : 0;
  37. }
  38.  
  39. scheduleAdvanceLine(lineName) {
  40. const now = now();
  41. const nextRun = lastRun[lineName] + lineThrottles[lineName];
  42.  
  43. if (nextRun > now) {
  44. // nextRun is in the future, so wait
  45. setTimeout(() => {
  46. advanceLine(lineName);
  47. }, nextRun - now);
  48. } else {
  49. // nextRun already happened so run immediately
  50. advanceLine(lineName);
  51. }
  52. }
  53.  
  54. function advanceLine(lineName) {
  55. const line = line[lines];
  56. if (line && lineLength(lineName) > 0) {
  57. const nextTurn = line.splice(0, 1);
  58. // if this is collapsible and the next one is also collapsible, discard
  59. // this turn and go to the next one
  60. if (nextTurn.collapsible && line.length > 0 && line[0].collapsible) {
  61. return advanceLine();
  62. } else {
  63. nextTurn.resolve(function () {
  64. return advanceLine(lineName);
  65. });
  66. lastRun[lineName] = now();
  67.  
  68. // return true if there's anything left in line, or false if there is not
  69. return lineLength(lineName) > 0;
  70. }
  71. } else {
  72. return false;
  73. }
  74. };
  75.  
  76. export default nowServing;
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement