1 | 'use strict'
|
2 |
|
3 | const {
|
4 | isEqual,
|
5 | isNotEqual,
|
6 | isGreaterThan,
|
7 | isGreaterThanOrEqual,
|
8 | isLessThan,
|
9 | isLessThanOrEqual,
|
10 | isInclude,
|
11 | isNotInclude,
|
12 | isSameSize,
|
13 | isNotSameSize,
|
14 | isRegexMatch,
|
15 | isNotRegexMatch
|
16 | } = require('./comparison')
|
17 |
|
18 | const {
|
19 | andLogical,
|
20 | orLogical,
|
21 | notLogical
|
22 | } = require('./logical')
|
23 |
|
24 | const cmpMap = {
|
25 | $eq: isEqual,
|
26 | $ne: isNotEqual,
|
27 | $gt: isGreaterThan,
|
28 | $gte: isGreaterThanOrEqual,
|
29 | $lt: isLessThan,
|
30 | $lte: isLessThanOrEqual,
|
31 | $in: isInclude,
|
32 | $nin: isNotInclude,
|
33 | $size: isSameSize,
|
34 | $nsize: isNotSameSize,
|
35 | $regex: isRegexMatch,
|
36 | $nregex: isNotRegexMatch,
|
37 | $and: choiceLogicalOperator,
|
38 | $or: choiceLogicalOperator,
|
39 | $all: choiceLogicalOperator,
|
40 | $not: choiceLogicalOperator
|
41 | }
|
42 |
|
43 | const logicalMap = {
|
44 | $and: andLogical,
|
45 | $or: orLogical,
|
46 | $all: andLogical,
|
47 | $not: notLogical
|
48 | }
|
49 |
|
50 | const allOperators = Object.keys(cmpMap)
|
51 |
|
52 | function interatorValues (value, operator, item) {
|
53 | if (!allOperators.includes(item)) {
|
54 | throw new Error(`The operator ${item} is incorrect. Valid operator: ${allOperators.join(', ')}`)
|
55 | }
|
56 | return cmpMap[item](value, operator[item], item)
|
57 | }
|
58 |
|
59 | function choiceLogicalOperator (value, operator, key) {
|
60 | const keys = Object.keys(operator)
|
61 | try {
|
62 | return logicalMap[key](keys, interatorValues, value, operator)
|
63 | } catch (err) {
|
64 | return keys.every(interatorValues.bind(null, value, operator))
|
65 | }
|
66 | }
|
67 |
|
68 | function compare (value, operator) {
|
69 | if (!operator) { throw new Error('You need to insert an operator') }
|
70 | const keys = Object.keys(operator)
|
71 | return interatorValues(value, operator, keys[0])
|
72 | }
|
73 |
|
74 | module.exports = {
|
75 | compare
|
76 | }
|