-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
53 lines (34 loc) · 1.03 KB
/
index.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
const Assert = require('assert')
const { AssertionError } = Assert
function fetchProp(obj, prop_or_props, assertType = x => {}) {
Assert(null != obj && typeof obj === 'object',
'The "obj" argument must be an object')
Assert(assertType instanceof Function,
'The "assertType" argument must be a function')
const props = Array.isArray(prop_or_props)
? prop_or_props
: [prop_or_props]
const x = props.reduce((o, prop) => {
if (!(typeof o === 'object' && prop in o)) {
throw new MissingPropError(`${propName(props)}`)
}
return o[prop]
}, obj)
const is_ok = assertType(x)
if (typeof is_ok === 'boolean' && !is_ok) {
throw new AssertionError({
message: `prop ${propName(props)} failed the assertion`
})
}
return x
}
function propName(props) {
return props.map(p => `"${p}"`).join('.')
}
class MissingPropError extends Error {
constructor(...args) {
super(...args)
this.name = 'MissingPropError'
}
}
module.exports = { fetchProp, MissingPropError, AssertionError }