import invariant from "invariant" ; import TinyQueue from "tinyqueue" ; export default class LoadQueue { constructor ( { threads } ) { this . _queue = new TinyQueue ( [ ] , ( a , b ) => a . priority ( ) - b . priority ( ) ) ; this . _availableThreads = threads ; } push ( task , priority ) { const t = { task , priority } ; this . _queue . push ( t ) ; setTimeout ( ( ) => { this . _run ( ) ; } , 0 ) ; return ( ) => { this . _queue = this . _queue . filter ( ( t1 ) => t1 !== t ) ; } ; } _run ( ) { while ( this . _availableThreads > 0 ) { if ( this . _queue . length === 0 ) { return ; } this . _availableThreads -- ; const t = this . _queue . pop ( ) ; const promise = t . task ( ) ; invariant ( typeof promise . then === "function" , `LoadQueue only supports loading Promises. Got ${ promise }` ) ; promise . then ( ( ) => { this . _availableThreads ++ ; this . _run ( ) ; } ) ; } } }