xref: /MusicFree/src/lib/react-native-vdebug/src/tool.js (revision 5589cdf32b2bb0f641e5ac7bf1f6152cd6b9b70e)
1function throttle(delay, noTrailing, callback, debounceMode) {
2    let timeoutID;
3    let lastExec = 0;
4    if (typeof noTrailing !== 'boolean') {
5        debounceMode = callback;
6        callback = noTrailing;
7        noTrailing = undefined;
8    }
9
10    function wrapper(...args) {
11        const self = this;
12        const elapsed = Number(new Date()) - lastExec;
13
14        function exec() {
15            lastExec = Number(new Date());
16            callback.apply(self, args);
17        }
18
19        function clear() {
20            timeoutID = undefined;
21        }
22
23        if (debounceMode && !timeoutID) {
24            exec();
25        }
26
27        if (timeoutID) {
28            clearTimeout(timeoutID);
29        }
30
31        if (!debounceMode && elapsed > delay) {
32            exec();
33        } else if (noTrailing !== true) {
34            timeoutID = setTimeout(
35                debounceMode ? clear : exec,
36                !debounceMode ? delay - elapsed : delay,
37            );
38        }
39    }
40
41    return wrapper;
42}
43
44function debounce(delay, atBegin, callback) {
45    return callback === undefined
46        ? throttle(delay, atBegin, false)
47        : throttle(delay, callback, atBegin !== false);
48}
49
50function replaceReg(str) {
51    const regStr = /\\|\$|\(|\)|\*|\+|\.|\[|\]|\?|\^|\{|\}|\|/gi;
52    return str.replace(regStr, function (input) {
53        return `\\${input}`;
54    });
55}
56
57module.exports = {
58    throttle,
59    debounce,
60    replaceReg,
61};
62