-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathindex.js
43 lines (36 loc) · 1013 Bytes
/
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
class Guards {
constructor () {
this.guardRegex = /[^=<>!']=[^=]/
this.templateRegex = /[^|]\|[^|]/
}
buildPredicate (constants, guard) {
// eslint-disable-next-line
return new Function(
'',
[
`const { ${this.destructureProps(constants)} } = ${JSON.stringify(constants)}`,
`return ${guard}`
].join(';')
)
}
destructureProps (constants) {
return Object.keys(constants).join(',')
}
equal (constants) {
const self = this
// Inline guards need filtering.
return template => template.raw[0]
.split(this.templateRegex)
.filter(g => g.trim() !== '')
.map((g, i) => {
// Remove break line and extract the guard.
const parts = g.trim().split(this.guardRegex)
return [
parts[0],
JSON.parse(`${parts[1].trim().replace(/'/g, '"')}`)
]
})
.find(g => self.buildPredicate(constants, g[0])())[1]
}
}
module.exports = (c, t) => (new Guards()).equal(c, t)