5
5
6
6
'use strict' ;
7
7
8
- const toReversed = require ( 'array.prototype.toreversed' ) ;
9
8
const getScope = require ( './eslint' ) . getScope ;
10
9
11
10
/**
@@ -29,30 +28,33 @@ function getVariable(variables, name) {
29
28
}
30
29
31
30
/**
32
- * List all variable in a given scope
33
- *
34
- * Contain a patch for babel-eslint to avoid https://github.com/babel/babel-eslint/issues/21
31
+ * Searches for a variable in the given scope.
35
32
*
36
33
* @param {Object } context The current rule context.
37
34
* @param {ASTNode } node The node to start looking from.
38
- * @returns {Array } The variables list
35
+ * @param {string } name The name of the variable to search.
36
+ * @returns {Object | undefined } Variable if the variable was found, undefined if not.
39
37
*/
40
- function variablesInScope ( context , node ) {
38
+ function getVariableFromContext ( context , node , name ) {
41
39
let scope = getScope ( context , node ) ;
42
- let variables = scope . variables ;
43
40
44
- while ( scope . type !== 'global' ) {
45
- scope = scope . upper ;
46
- variables = scope . variables . concat ( variables ) ;
47
- }
48
- if ( scope . childScopes . length ) {
49
- variables = scope . childScopes [ 0 ] . variables . concat ( variables ) ;
50
- if ( scope . childScopes [ 0 ] . childScopes . length ) {
51
- variables = scope . childScopes [ 0 ] . childScopes [ 0 ] . variables . concat ( variables ) ;
41
+ while ( scope ) {
42
+ let variable = getVariable ( scope . variables , name ) ;
43
+
44
+ if ( ! variable && scope . childScopes . length ) {
45
+ variable = getVariable ( scope . childScopes [ 0 ] . variables , name ) ;
46
+
47
+ if ( ! variable && scope . childScopes [ 0 ] . childScopes . length ) {
48
+ variable = getVariable ( scope . childScopes [ 0 ] . childScopes [ 0 ] . variables , name ) ;
49
+ }
52
50
}
53
- }
54
51
55
- return toReversed ( variables ) ;
52
+ if ( variable ) {
53
+ return variable ;
54
+ }
55
+ scope = scope . upper ;
56
+ }
57
+ return undefined ;
56
58
}
57
59
58
60
/**
@@ -63,7 +65,7 @@ function variablesInScope(context, node) {
63
65
* @returns {ASTNode|null } Return null if the variable could not be found, ASTNode otherwise.
64
66
*/
65
67
function findVariableByName ( context , node , name ) {
66
- const variable = getVariable ( variablesInScope ( context , node ) , name ) ;
68
+ const variable = getVariableFromContext ( context , node , name ) ;
67
69
68
70
if ( ! variable || ! variable . defs [ 0 ] || ! variable . defs [ 0 ] . node ) {
69
71
return null ;
@@ -93,6 +95,6 @@ module.exports = {
93
95
findVariable,
94
96
findVariableByName,
95
97
getVariable,
96
- variablesInScope ,
98
+ getVariableFromContext ,
97
99
getLatestVariableDefinition,
98
100
} ;
0 commit comments