-
Notifications
You must be signed in to change notification settings - Fork 2
/
index.js
36 lines (30 loc) · 1.27 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
/* eslint-disable no-new-func, no-useless-escape */
const safeRegexPattern = /[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g
const isExpression = /(AND|OR|!|&|\|)/
const booleanExpression = require('boolean-expression')
module.exports = function getValidate (expression) {
if (Array.isArray(expression)) expression = expression.join(' ')
if (!isExpression.test(expression)) expression = expression.split(' ').filter(Boolean).join(' && ')
expression = booleanExpression(expression)
const checkArray = expression.toString(function (value) {
return `scopes.includes(${JSON.stringify(value)})`
})
const checkSet = expression.toString(function (value) {
return `scopes.has(${JSON.stringify(value)})`
})
const declations = []
const checkString = expression.toString(function (value, i) {
value = value.replace(safeRegexPattern, '\\$&')
declations.push(`const a${i} = /(?:^|\\\s)${value}(?:\\\s|$)/`)
return `a${i}.test(scopes)`
})
const validate = new Function([declations.join('\n'),
'return function validate (scopes) {',
` if (typeof scopes === 'string') return ${checkString}`,
` if (scopes instanceof Set) return ${checkSet}`,
` return ${checkArray}`,
'}'
].join('\n'))()
validate.scopes = expression.toTokens()
return validate
}