Skip to content

Commit

Permalink
Use at() instead of direct access
Browse files Browse the repository at this point in the history
  • Loading branch information
ShridharGoel committed Jul 3, 2024
1 parent 15361c2 commit 76202c5
Show file tree
Hide file tree
Showing 4 changed files with 68 additions and 1 deletion.
2 changes: 2 additions & 0 deletions eslint-plugin-expensify/CONST.js
Original file line number Diff line number Diff line change
Expand Up @@ -28,5 +28,7 @@ module.exports = {
MUST_USE_VARIABLE_FOR_ASSIGNMENT: '{{key}} must be assigned as a variable instead of direct assignment.',
NO_DEFAULT_PROPS: 'defaultProps should not be used in function components. Use default Arguments instead.',
USE_PERIODS_ERROR_MESSAGES: 'Use periods at the end of error messages.',
USE_DOUBLE_NEGATION_INSTEAD_OF_BOOLEAN: 'Use !! instead of Boolean().',
PREFER_AT: 'Use the .at() method for array element access',
},
};
26 changes: 26 additions & 0 deletions eslint-plugin-expensify/prefer-at.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
const message = require('./CONST').MESSAGE.PREFER_AT;

module.exports = {
meta: {
fixable: 'code',
},

create(context) {
return {
MemberExpression(node) {
// Check if we are accessing an array element directly
if (node.object.type === 'Identifier' && node.property.type === 'Literal' && typeof node.property.value === 'number') {
context.report({
node,
message,
fix(fixer) {
const arrayName = node.object.name;
const indexValue = node.property.value;
return fixer.replaceText(node, `${arrayName}.at(${indexValue})`);
},
});
}
},
};
},
};
37 changes: 37 additions & 0 deletions eslint-plugin-expensify/tests/prefer-at.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
const RuleTester = require('eslint').RuleTester;
const rule = require('../prefer-at');
const message = require('../CONST').MESSAGE.PREFER_AT;

const ruleTester = new RuleTester({
parserOptions: {
ecmaVersion: 6,
sourceType: 'module',
},
});

ruleTester.run('prefer-at', rule, {
valid: [
{
code: 'example.at(0)',
},
{
code: 'test.at(1)',
},
],
invalid: [
{
code: 'example[0]',
output: 'example.at(0)',
errors: [{
message,
}],
},
{
code: 'test[1]',
output: 'test.at(1)',
errors: [{
message,
}],
},
],
});
4 changes: 3 additions & 1 deletion rules/expensify.js
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,8 @@ module.exports = {
'rulesdir/no-call-actions-from-actions': 'error',
'rulesdir/no-api-side-effects-method': 'error',
'rulesdir/prefer-localization': 'error',
'rulesdir/use-double-negation-instead-of-boolean': 'error',
'rulesdir/prefer-at': 'error',
'no-restricted-imports': ['error', {
paths: [{
name: 'react-native',
Expand All @@ -27,4 +29,4 @@ module.exports = {
}],
}],
},
};
};

0 comments on commit 76202c5

Please sign in to comment.