-
Notifications
You must be signed in to change notification settings - Fork 0
/
utils.js
executable file
·71 lines (59 loc) · 2.02 KB
/
utils.js
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
export function assertTrue(expr = null, debugInfo) {
if (!!expr !== true) {
if (debugInfo) console.debug('AssertTrue:', debugInfo);
throw new Error(`AssertTrue: given expression is falsy.`);
}
}
export function assertEqual(exprA, exprB, debugInfo) {
if (typeof (exprA) === 'object' || typeof (exprB) === 'object') {
console.error("assertEqual: Can't compare objects:", exprA, exprB);
}
if (exprA !== exprB) {
if (debugInfo) console.debug('assertEqual:', debugInfo);
throw new Error(`assertEqual:\n${exprA}\n\n!==\n\n${exprB}`);
}
}
export function isDomElement(entity) {
return typeof entity === 'object' && entity.nodeType !== undefined;
}
export async function waitFor(funOrMs, config) {
return {
'number': () => waitForMs(funOrMs, config),
'function': () => waitForFun(funOrMs, config),
}[typeof (funOrMs)]();
}
/**
* Waits until `fun` resolves into a truthy value,
* every `checkIntervalTime` ms, `retries` times.
* @param {Function} fun - a function to execute every
* @param {Object} config
* @param {Number} config.checkIntervalTime - re-check every miliseconds
* @param {Number} config.retries - How many times to retry before failing with a timeout error
*/
export async function waitForFun(fun, { checkIntervalTime = 200, retries = 10 }) {
if (typeof fun !== 'function') {
throw new Error('waitFor only accepts a function as argument')
}
return new Promise((resolve, _) => {
if (!!fun()) {
return resolve(fun());
}
function check() {
if (!!fun()) {
clearInterval(intervalId);
clearTimeout(timeoutId);
return resolve(fun());
}
}
const intervalId = setInterval(check, checkIntervalTime);
const timeoutId = setTimeout(() => {
clearInterval(intervalId);
throw new Error(`timeout on waitFor(${fun})`);
}, checkIntervalTime * retries + Math.ceil(checkIntervalTime * 0.1));
});
}
export async function waitForMs(miliseconds) {
return new Promise((resolve, _) => {
setTimeout(resolve(), miliseconds);
})
}