Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -81,88 +81,19 @@ function main( context ) {
break;
}

/**
* Sorts the variable declarations by name length.
*
* @private
* @param {Object} a - input object
* @param {Object} b - comparison object
* @returns {number} number indicating sort order
*/
function sortVars( a, b ) {
if ( fun( a.name.length, b.name.length ) ) {
return 1;
}
return -1;
}

/**
* Reports the error message.
*
* @private
* @param {string} msg - error message
* @param {ASTNode} node - node to fix
* @param {Object} loc - lines of code (object with `start` and `end` properties)
*/
function report( msg, node ) {
function report( msg, loc ) {
context.report({
'node': null,
'message': msg,
'loc': node.loc,
'fix': fix
'loc': loc
});

/**
* Fixes the lint error by reordering the variable declarations inside of the function.
*
* @private
* @param {Function} fixer - ESLint fixer
* @returns {(Object|null)} fix or null
*/
function fix( fixer ) {
var replacingText;
var declarations;
var startRange;
var endRange;
var source;
var elem;
var body;
var i;
var j;

declarations = [];
replacingText = '';
body = node.body.body;
source = context.getSourceCode();

for ( i = 0; i < body.length; i++ ) {
elem = body[ i ];
if ( elem.type === 'VariableDeclaration' && elem.kind === 'var' ) {
declarations.push({
'text': source.getText( elem ),
'name': elem.declarations[ 0 ].id.name,
'col': elem.loc.start.column
});
if ( declarations.length === 1 ) {
startRange = elem.range[ 0 ] - elem.loc.start.column;
}
endRange = elem.range[ 1 ];
}
}

declarations.sort( sortVars );

for ( i = 0; i < declarations.length; i++ ) {
for ( j = 0; j < declarations[ i ].col; j++ ) {
replacingText += '\t';
}
replacingText += declarations[ i ].text;
if ( i !== declarations.length -1 ) {
replacingText += '\n';
}
}

return fixer.replaceTextRange( [ startRange, endRange ], replacingText ); // eslint-disable-line max-len
}
}

/**
Expand All @@ -186,7 +117,7 @@ function main( context ) {
if ( elem.type === 'VariableDeclaration' && elem.kind === 'var' ) {
name = elem.declarations[ 0 ].id.name;
if ( prevLength && !fun( name.length, prevLength ) ) {
return report( 'Variable declarations inside of function are not ordered by length (in '+ order +' order)', node );
return report( 'Variable declarations inside of function are not ordered by length (in '+ order +' order)', node.loc );
}
prevLength = name.length;
}
Expand All @@ -204,11 +135,9 @@ function main( context ) {

rule = {
'meta': {
'type': 'layout',
'docs': {
'description': 'require variable declarations inside of functions to be ordered by length'
},
'fixable': 'code',
'schema': [
{
'order': [ 'increasing', 'decreasing' ]
Expand Down
Loading
Loading