PriorityQueue.js 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138
  1. // Fires at the end of the frame and before the next one
  2. function enqueueMicrotask( callback ) {
  3. Promise.resolve().then( callback );
  4. }
  5. class PriorityQueue {
  6. constructor() {
  7. // options
  8. this.maxJobs = 6;
  9. this.items = [];
  10. this.callbacks = new Map();
  11. this.currJobs = 0;
  12. this.scheduled = false;
  13. this.autoUpdate = true;
  14. this.priorityCallback = () => {
  15. throw new Error( 'PriorityQueue: PriorityCallback function not defined.' );
  16. };
  17. }
  18. sort() {
  19. const priorityCallback = this.priorityCallback;
  20. const items = this.items;
  21. items.sort( ( a, b ) => {
  22. return priorityCallback( a ) - priorityCallback( b );
  23. } );
  24. }
  25. add( item, callback ) {
  26. return new Promise( ( resolve, reject ) => {
  27. const prCallback = ( ...args ) => callback( ...args ).then( resolve ).catch( reject );
  28. const items = this.items;
  29. const callbacks = this.callbacks;
  30. items.push( item );
  31. callbacks.set( item, prCallback );
  32. if ( this.autoUpdate ) {
  33. this.scheduleJobRun();
  34. }
  35. } );
  36. }
  37. remove( item ) {
  38. const items = this.items;
  39. const callbacks = this.callbacks;
  40. const index = items.indexOf( item );
  41. if ( index !== - 1 ) {
  42. items.splice( index, 1 );
  43. callbacks.delete( item );
  44. }
  45. }
  46. tryRunJobs() {
  47. this.sort();
  48. const items = this.items;
  49. const callbacks = this.callbacks;
  50. const maxJobs = this.maxJobs;
  51. let currJobs = this.currJobs;
  52. while ( maxJobs > currJobs && items.length > 0 ) {
  53. currJobs ++;
  54. const item = items.pop();
  55. const callback = callbacks.get( item );
  56. callbacks.delete( item );
  57. callback( item )
  58. .then( () => {
  59. this.currJobs --;
  60. if ( this.autoUpdate ) {
  61. this.scheduleJobRun();
  62. }
  63. } )
  64. .catch( () => {
  65. this.currJobs --;
  66. if ( this.autoUpdate ) {
  67. this.scheduleJobRun();
  68. }
  69. } );
  70. }
  71. this.currJobs = currJobs;
  72. }
  73. scheduleJobRun() {
  74. if ( ! this.scheduled ) {
  75. enqueueMicrotask( () => {
  76. this.tryRunJobs();
  77. this.scheduled = false;
  78. } );
  79. this.scheduled = true;
  80. }
  81. }
  82. }
  83. export { PriorityQueue };