UNPKG

857 BJavaScriptView Raw
1/**
2 * Mutual exclude for JavaScript.
3 *
4 * @module mutex
5 */
6
7/**
8 * @callback mutex
9 * @param {function():void} cb Only executed when this mutex is not in the current stack
10 * @param {function():void} [elseCb] Executed when this mutex is in the current stack
11 */
12
13/**
14 * Creates a mutual exclude function with the following property:
15 *
16 * ```js
17 * const mutex = createMutex()
18 * mutex(() => {
19 * // This function is immediately executed
20 * mutex(() => {
21 * // This function is not executed, as the mutex is already active.
22 * })
23 * })
24 * ```
25 *
26 * @return {mutex} A mutual exclude function
27 * @public
28 */
29export const createMutex = () => {
30 let token = true
31 return (f, g) => {
32 if (token) {
33 token = false
34 try {
35 f()
36 } finally {
37 token = true
38 }
39 } else if (g !== undefined) {
40 g()
41 }
42 }
43}