Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add prefer-string-slice rule - fixes #65 #67

Closed
wants to merge 12 commits into from
3 changes: 2 additions & 1 deletion index.js
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,8 @@ module.exports = {
'unicorn/number-literal-case': 'error',
'unicorn/no-array-instanceof': 'error',
'unicorn/no-new-buffer': 'error',
'unicorn/no-hex-escape': 'error'
'unicorn/no-hex-escape': 'error',
'unicorn/prefer-string-slice': 'error'
}
}
}
Expand Down
20 changes: 20 additions & 0 deletions rules/prefer-string-slice.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
'use strict';

const create = context => {
return {
Identifier: node => {
const name = node.name;

if (name === 'substr' || name === 'substring') {
context.report({
node,
message: 'Use String.slice instead of String.substr or String.substring.'
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Use \`String.slice\` instead of \`String.${name}\`.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Ah, of course, much better, sorted :)

});
}
}
};
};

module.exports = {
create
};
47 changes: 47 additions & 0 deletions test/prefer-string-slice.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
import test from 'ava';
import avaRuleTester from 'eslint-ava-rule-tester';
import rule from '../rules/prefer-string-slice';

const ruleTester = avaRuleTester(test, {
env: {
es6: true
}
});

const error = {
ruleId: 'prefer-string-slice',
message: 'Use String.slice instead of String.substr or String.substring.'
};

ruleTester.run('prefer-string-slice', rule, {
valid: [
'const foo = bar.slice(1)',
`const foo = bar.slice(function() { return 1; }, 2);`
],
invalid: [
{
code: 'const foo = bar.substr(1)',
errors: [error]
},
{
code: 'const foo = bar.substr(1,2)',
errors: [error]
},
{
code: `const foo = bar.substr(function() { return 1; }, 2);`,
errors: [error]
},
{
code: 'const foo = bar.substring(1)',
errors: [error]
},
{
code: 'const foo = bar.substring(1,2)',
errors: [error]
},
{
code: `const foo = bar.substr(function() { return 1; }, 2);`,
errors: [error]
}
]
});