File size: 1,394 Bytes
1e92f2d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
export const MILLISECONDS_PER_SECOND = 1000;

let lastNow = Date.now();
/**
 * Returns the time in miliseconds.
 * A strictly increasing version of Date.now()
 *
 * Gives us some minimimal guarentees about user clocks.
 */
export function monotonicNow(): number {
	const maybeNow = Date.now();

	lastNow = lastNow < maybeNow ? maybeNow : lastNow + 1;

	return lastNow;
}

/**
 * Timeouts a promise. Returns timeoutValue in event of timeout.
 * @param promise The promise to timeout
 * @param timeoutMilliseconds The timeout time in milliseconds
 */
export function timeoutPromise< T >(
	promise: Promise< T >,
	timeoutMilliseconds: number
): Promise< T | null > {
	return Promise.race( [
		promise,
		new Promise< null >( ( _res, rej ) =>
			setTimeout(
				() => rej( new Error( `Promise has timed-out after ${ timeoutMilliseconds }ms.` ) ),
				timeoutMilliseconds
			)
		),
	] );
}

/**
 * Wraps an async function so that if it is called multiple times it will just return the same promise - until the promise is fulfilled.
 *
 * Once the promise has been fulfilled it will reset.
 * @param f The function to wrap
 */
export function asyncOneAtATime< T >( f: () => Promise< T > ): () => Promise< T > {
	let lastPromise: Promise< T > | null = null;
	return () => {
		if ( ! lastPromise ) {
			lastPromise = f().finally( () => {
				lastPromise = null;
			} );
		}
		return lastPromise;
	};
}