Skip to content
98 changes: 83 additions & 15 deletions lib/node_modules/@stdlib/_tools/eslint/rules/vars-order/lib/main.js
Original file line number Diff line number Diff line change
Expand Up @@ -81,21 +81,6 @@ function main( context ) {
break;
}

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

/**
* Checks whether the variable declarations inside of the supplied node are ordered.
*
Expand All @@ -122,6 +107,87 @@ function main( context ) {
prevLength = name.length;
}
}

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

/**
* 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 j;

declarations = [];
replacingText = '';
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

/**
* 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;
}
}
}

return {
Expand All @@ -135,9 +201,11 @@ 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