-
Notifications
You must be signed in to change notification settings - Fork 47
/
eslint-local-rules.js
55 lines (48 loc) · 2.05 KB
/
eslint-local-rules.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
/* ©️ 2016 - present FlowCrypt a.s. Limitations apply. Contact [email protected] */
const DO_USE_LOOPS = `
There should be only one obvious way to do a thing.
- JS already has good tooling for loops
- It's hard to return a value from inside .each/map/forEach and friends
- breaking from inside .each/map/forEach loop uses non-obvious semantics
- consistency matters
// Allowed array loops:
for (const v of arr) { } // loop through values
for (let i = 0; i < arr.length; i++) { } // loop through indexes
// Allowed jQuery selector loops:
for (const element of $('selector')) { } // selector results are iterable
// Allowed Object loops:
for (const v of Object.values(obj)) { } // get values, no need obj.hasOwnProperty
for (const v of Object.keys(obj)) { } // get keys, no need obj.hasOwnProperty`;
const DO_NOT_USE_EACH = `Using .each or .forEach for looping is heavily discouraged. ${DO_USE_LOOPS}`;
const DO_NOT_USE_MAP_EXPR_STMT = 'Use .map() when you want to transform an array,' + ` not as a substitute for loops. ${DO_USE_LOOPS}`;
module.exports = {
'standard-loops': {
meta: {
docs: {
description: 'disallow identifiers',
category: 'Possible Errors',
recommended: false,
},
schema: [],
},
create: context => {
return {
CallExpression: node => {
if (node.callee.property) {
const propertyName = node.callee.property.name;
if (propertyName === 'forEach' || propertyName === 'each') {
context.report({ node, message: DO_NOT_USE_EACH });
} else if (propertyName === 'map') {
const sourceCode = context.sourceCode ?? context.getSourceCode();
const ancestors = sourceCode.getAncestors ? sourceCode.getAncestors(node) : context.getAncestors();
const parent = ancestors[ancestors.length - 1];
if (parent && parent.type === 'ExpressionStatement') {
context.report({ node, message: DO_NOT_USE_MAP_EXPR_STMT });
}
}
}
},
};
},
},
};