Skip to content

Commit

Permalink
Suggest to replace indexOf(..., '') === 0 with _.startsWith. Fixes wi…
Browse files Browse the repository at this point in the history
  • Loading branch information
Jignesh Kakadiya committed Dec 18, 2015
1 parent 9f72cc3 commit 02d1b60
Show file tree
Hide file tree
Showing 2 changed files with 62 additions and 0 deletions.
28 changes: 28 additions & 0 deletions lib/rules/prefer-startswith.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
/**
* @fileoverview Rule to check if a call to _.indexOf === 0 should be a call to _.startsWith
*/
'use strict';

//------------------------------------------------------------------------------
// Rule Definition
//------------------------------------------------------------------------------

module.exports = function (context) {
var lodashUtil = require('../util/lodashUtil');

function isExpectingZeroIndex(operator) {
if (operator && operator.type === 'BinaryExpression' && operator.right) {
return operator.right.value === 0;
}

return false;
}

return {
CallExpression: function (node) {
if (lodashUtil.isCallToMethod(node, 'indexOf') && isExpectingZeroIndex(node.parent)) {
context.report(node, 'Prefer _.startsWith instead of _.indexOf(...,) === 0');
}
}
};
};
34 changes: 34 additions & 0 deletions tests/lib/rules/prefer-startswith.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
'use strict';

// ------------------------------------------------------------------------------
// Requirements
// ------------------------------------------------------------------------------

var rule = require('../../../lib/rules/prefer-startswith');
var RuleTester = require('eslint').RuleTester;

// ------------------------------------------------------------------------------
// Tests
// ------------------------------------------------------------------------------

var ruleTester = new RuleTester();
var toErrorObject = require('../testUtil/toErrorObject')
.fromMessage('Prefer _.startsWith instead of _.indexOf(...,) === 0');

ruleTester.run('prefer-startswith', rule, {
valid: [
'_.indexOf(a, b) == 10',
'_.indexOf(a, b) === 10',
'_.indexOf(a, b) === -1',
'if (_.indexOf(a.b.c, b.c)) {}'
],
invalid: [
'_.indexOf(a, b) === 0',
'_.indexOf(a.b.c, "b") == 0',
'_.indexOf(a, b) !== 0',
'_.indexOf(a.b.c.d, "b") != 0',
'_.indexOf(a.b, b.c) === 0',
'_.indexOf(a.b.c, b.c) !== 0',
'if (_.indexOf(a.b.c, b.c) === 000) {}'
].map(toErrorObject)
});

0 comments on commit 02d1b60

Please sign in to comment.