-
-
Notifications
You must be signed in to change notification settings - Fork 13
Expand file tree
/
Copy pathprefer-string-fromcharcode.ts
More file actions
60 lines (56 loc) · 1.68 KB
/
Copy pathprefer-string-fromcharcode.ts
File metadata and controls
60 lines (56 loc) · 1.68 KB
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
56
57
58
59
60
import type {Rule} from 'eslint';
import type {CallExpression, Expression, SpreadElement} from 'estree';
const FROM_CHARCODE_LIMIT = 0x10000;
function isFromCharCodeSafeLiteral(node: Expression | SpreadElement): boolean {
return (
node.type === 'Literal' &&
typeof node.value === 'number' &&
Number.isInteger(node.value) &&
node.value >= 0 &&
node.value < FROM_CHARCODE_LIMIT
);
}
export const preferStringFromCharCode: Rule.RuleModule = {
meta: {
type: 'suggestion',
docs: {
description:
'Prefer String.fromCharCode() over String.fromCodePoint() for code points below 0x10000',
recommended: true
},
fixable: 'code',
schema: [],
messages: {
preferFromCharCode:
'String.fromCharCode is faster than String.fromCodePoint for code points below 0x10000.'
}
},
create(context) {
return {
CallExpression(node: CallExpression) {
if (node.callee.type !== 'MemberExpression') return;
if (node.callee.computed) return;
if (
node.callee.object.type !== 'Identifier' ||
node.callee.object.name !== 'String'
)
return;
if (
node.callee.property.type !== 'Identifier' ||
node.callee.property.name !== 'fromCodePoint'
)
return;
if (node.arguments.length === 0) return;
if (!node.arguments.every(isFromCharCodeSafeLiteral)) return;
const property = node.callee.property;
context.report({
node: property,
messageId: 'preferFromCharCode',
fix(fixer) {
return fixer.replaceText(property, 'fromCharCode');
}
});
}
};
}
};