Advertisement
Guest User

Untitled

a guest
Dec 10th, 2019
109
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. let actionsQueue = {};
  2. let defaultMaxActionsProgressing = 50;
  3. let lastActionId = 0;
  4.  
  5. export const getQueue = (key) => {
  6.     if (!actionsQueue[key]) {
  7.         actionsQueue[key] = {
  8.             max: defaultMaxActionsProgressing,
  9.             actions: []
  10.         };
  11.     }
  12.     return actionsQueue[key];
  13. };
  14.  
  15. export const setMax = (key, max) => {
  16.     getQueue(key).max = max;
  17. };
  18.  
  19. const removeFromQueue = (key, id) => {
  20.     let q = getQueue(key);
  21.     q.actions = q.actions.filter(a => a.id !== id);
  22. };
  23.  
  24. const execute = (key, action) => {
  25.     // setting action to progressing
  26.     action.progressing = true;
  27.     action.fn(() => {
  28.         removeFromQueue(key, action.id);
  29.         executeQueue(key);
  30.     });
  31. };
  32.  
  33. const executeQueue = (key) => {
  34.     let q = getQueue(key);
  35.     const actualProgressing = q.actions.filter(a => a.progressing).length;
  36.     if (q.actions.length === 0 || actualProgressing >= q.max) {
  37.         return;
  38.     }
  39.     q.actions
  40.         .filter(a => !a.progressing)
  41.         .slice(0, q.max - actualProgressing)
  42.         .map(action => execute(key, action));
  43. };
  44.  
  45. export const addToExecute = (key, fn) => {
  46.     let q = getQueue(key);
  47.     q.actions.push({
  48.         id: lastActionId,
  49.         key,
  50.         fn,
  51.         progressing: false
  52.     });
  53.     lastActionId++;
  54.     executeQueue(key);
  55. };
  56.  
  57. // WYWOŁANIE
  58.  
  59. setMax('test-key', 4);
  60.  
  61. console.time('1')
  62. console.time('2')
  63. console.time('3')
  64. console.time('4')
  65. console.time('5')
  66.  
  67. // PIERWSZE WYWOŁANIE
  68. addToExecute('test-key', (end) => {
  69.   setTimeout(() => {
  70.     console.timeEnd('1');
  71.     end()
  72.   }, 200);
  73. })
  74.  
  75. // DRUGIE WYWOŁANIE
  76. addToExecute('test-key', (end) => {
  77.   setTimeout(() => {
  78.     console.timeEnd('2');
  79.     end()
  80.   }, 200);
  81. })
  82.  
  83. // TRZECIE WYWOŁANIE
  84. addToExecute('test-key', (end) => {
  85.   setTimeout(() => {
  86.     console.timeEnd('3');
  87.     end()
  88.   }, 200);
  89. })
  90.  
  91. addToExecute('test-key', (end) => {
  92.   setTimeout(() => {
  93.     console.timeEnd('4');
  94.     end()
  95.   }, 200);
  96. })
  97.  
  98. addToExecute('test-key', (end) => {
  99.   setTimeout(() => {
  100.     console.timeEnd('5');
  101.     end()
  102.   }, 200);
  103. })
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement