-
Notifications
You must be signed in to change notification settings - Fork 2.9k
/
index.ts
71 lines (59 loc) · 2.13 KB
/
index.ts
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
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
import Onyx from 'react-native-onyx';
import Sound from 'react-native-sound';
import type {ValueOf} from 'type-fest';
import ONYXKEYS from '@src/ONYXKEYS';
import config from './config';
let isMuted = false;
Onyx.connect({
key: ONYXKEYS.USER,
callback: (val) => (isMuted = !!val?.isMutedAllSounds),
});
const SOUNDS = {
DONE: 'done',
SUCCESS: 'success',
ATTENTION: 'attention',
RECEIVE: 'receive',
} as const;
/**
* Creates a version of the given function that, when called, queues the execution and ensures that
* calls are spaced out by at least the specified `minExecutionTime`, even if called more frequently. This allows
* for throttling frequent calls to a function, ensuring each is executed with a minimum `minExecutionTime` between calls.
* Each call returns a promise that resolves when the function call is executed, allowing for asynchronous handling.
*/
function withMinimalExecutionTime<F extends (...args: Parameters<F>) => ReturnType<F>>(func: F, minExecutionTime: number) {
const queue: Array<[() => ReturnType<F>, (value?: unknown) => void]> = [];
let timerId: NodeJS.Timeout | null = null;
function processQueue() {
if (queue.length > 0) {
const next = queue.shift();
if (!next) {
return;
}
const [nextFunc, resolve] = next;
nextFunc();
resolve();
timerId = setTimeout(processQueue, minExecutionTime);
} else {
timerId = null;
}
}
return function (...args: Parameters<F>) {
return new Promise((resolve) => {
queue.push([() => func(...args), resolve]);
if (!timerId) {
// If the timer isn't running, start processing the queue
processQueue();
}
});
};
}
const playSound = (soundFile: ValueOf<typeof SOUNDS>) => {
const sound = new Sound(`${config.prefix}${soundFile}.mp3`, Sound.MAIN_BUNDLE, (error) => {
if (error || isMuted) {
return;
}
sound.play();
});
};
export {SOUNDS};
export default withMinimalExecutionTime(playSound, 300);