1 | /**
|
---|
2 | * Extractor function for a BinaryExpression type value node.
|
---|
3 | * A binary expression has a left and right side separated by an operator
|
---|
4 | * such as `a + b`.
|
---|
5 | *
|
---|
6 | * @param - value - AST Value object with type `BinaryExpression`
|
---|
7 | * @returns - The extracted value converted to correct type.
|
---|
8 | */
|
---|
9 | export default function extractValueFromBinaryExpression(value) {
|
---|
10 | // eslint-disable-next-line global-require
|
---|
11 | const getValue = require('.').default;
|
---|
12 | const { operator, left, right } = value;
|
---|
13 | const leftVal = getValue(left);
|
---|
14 | const rightVal = getValue(right);
|
---|
15 |
|
---|
16 | switch (operator) {
|
---|
17 | case '==':
|
---|
18 | return leftVal == rightVal; // eslint-disable-line
|
---|
19 | case '!=':
|
---|
20 | return leftVal != rightVal; // eslint-disable-line
|
---|
21 | case '===':
|
---|
22 | return leftVal === rightVal;
|
---|
23 | case '!==':
|
---|
24 | return leftVal !== rightVal;
|
---|
25 | case '<':
|
---|
26 | return leftVal < rightVal;
|
---|
27 | case '<=':
|
---|
28 | return leftVal <= rightVal;
|
---|
29 | case '>':
|
---|
30 | return leftVal > rightVal;
|
---|
31 | case '>=':
|
---|
32 | return leftVal >= rightVal;
|
---|
33 | case '<<':
|
---|
34 | return leftVal << rightVal; // eslint-disable-line no-bitwise
|
---|
35 | case '>>':
|
---|
36 | return leftVal >> rightVal; // eslint-disable-line no-bitwise
|
---|
37 | case '>>>':
|
---|
38 | return leftVal >>> rightVal; // eslint-disable-line no-bitwise
|
---|
39 | case '+':
|
---|
40 | return leftVal + rightVal;
|
---|
41 | case '-':
|
---|
42 | return leftVal - rightVal;
|
---|
43 | case '*':
|
---|
44 | return leftVal * rightVal;
|
---|
45 | case '/':
|
---|
46 | return leftVal / rightVal;
|
---|
47 | case '%':
|
---|
48 | return leftVal % rightVal;
|
---|
49 | case '|':
|
---|
50 | return leftVal | rightVal; // eslint-disable-line no-bitwise
|
---|
51 | case '^':
|
---|
52 | return leftVal ^ rightVal; // eslint-disable-line no-bitwise
|
---|
53 | case '&':
|
---|
54 | return leftVal & rightVal; // eslint-disable-line no-bitwise
|
---|
55 | case 'in':
|
---|
56 | try {
|
---|
57 | return leftVal in rightVal;
|
---|
58 | } catch (err) {
|
---|
59 | return false;
|
---|
60 | }
|
---|
61 | case 'instanceof':
|
---|
62 | if (typeof rightVal !== 'function') {
|
---|
63 | return false;
|
---|
64 | }
|
---|
65 | return leftVal instanceof rightVal;
|
---|
66 | default:
|
---|
67 | return undefined;
|
---|
68 | }
|
---|
69 | }
|
---|