-
Notifications
You must be signed in to change notification settings - Fork 0
/
invariant.js
41 lines (33 loc) · 835 Bytes
/
invariant.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
const fmt = require("sprintf-js").sprintf
/**
* @param {boolean} predicate
* @param {string | Function} Err
* @param {any[]} ...format
*
* @throws {any} given Err when predicate is "true"
*/
function invariant(predicate, Err, ...format) {
if (Boolean(predicate) === false) {
return undefined
}
if (typeof Err === "string") {
throw new Error(fmt(Err, ...format))
}
if (typeof Err === "function") {
const message = format.shift()
throw new Err(fmt(message, ...format))
}
throw Err
}
function reject(predicate, Err, ...format) {
try {
invariant(predicate, Err, ...format)
return Promise.resolve(undefined)
} catch (error) {
return Promise.reject(error)
}
}
invariant.reject = reject
module.exports = invariant
module.exports.reject = reject
module.exports.default = invariant