function isPrimitive ( value ) { return value === null || ( typeof value !== 'object' && typeof value !== 'function' ) ; } const wm = new WeakMap < any , any > ( ) ; export function safeRace < T > ( contenders ) { let deferred ; const result = new Promise < T > ( ( resolve , reject ) => { deferred = { resolve , reject } ; for ( const contender of contenders ) { if ( isPrimitive ( contender ) ) { Promise . resolve ( contender ) . then ( resolve , reject ) ; continue ; } let record = wm . get ( contender ) ; if ( record === undefined ) { record = { deferreds : new Set ( [ deferred ] ) , settled : false } ; wm . set ( contender , record ) ; Promise . resolve ( contender ) . then ( ( value ) => { for ( const { resolve } of record . deferreds ) { resolve ( value ) ; } record . deferreds . clear ( ) ; record . settled = true ; } , ( err ) => { for ( const { reject } of record . deferreds ) { reject ( err ) ; } record . deferreds . clear ( ) ; record . settled = true ; } ) ; } else if ( record . settled ) { Promise . resolve ( contender ) . then ( resolve , reject ) ; } else { record . deferreds . add ( deferred ) ; } } } ) ; return result . finally ( ( ) => { for ( const contender of contenders ) { if ( ! isPrimitive ( contender ) ) { const record = wm . get ( contender ) ; record . deferreds . delete ( deferred ) ; } } } ) ; }