-
-
Notifications
You must be signed in to change notification settings - Fork 8
Expand file tree
/
Copy pathprefer-date-now.ts
More file actions
84 lines (78 loc) · 2.34 KB
/
prefer-date-now.ts
File metadata and controls
84 lines (78 loc) · 2.34 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
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
import type {Rule} from 'eslint';
import type {CallExpression, UnaryExpression, NewExpression} from 'estree';
function getDateNowReplacement(node: NewExpression): string | null {
if (node.type !== 'NewExpression' || node.arguments.length !== 0) {
return null;
}
if (node.callee.type === 'Identifier' && node.callee.name === 'Date') {
return 'Date.now()';
}
if (
node.callee.type === 'MemberExpression' &&
node.callee.object.type === 'Identifier' &&
(node.callee.object.name === 'window' ||
node.callee.object.name === 'globalThis') &&
node.callee.property.type === 'Identifier' &&
node.callee.property.name === 'Date' &&
!node.callee.computed
) {
return `${node.callee.object.name}.Date.now()`;
}
return null;
}
export const preferDateNow: Rule.RuleModule = {
meta: {
type: 'suggestion',
docs: {
description:
'Prefer Date.now() over new Date().getTime() and +new Date()',
recommended: true
},
fixable: 'code',
schema: [],
messages: {
preferDateNow: 'Use Date.now() to avoid allocating a new Date object.'
}
},
create(context) {
return {
// new Date().getTime()
CallExpression(node: CallExpression) {
if (
node.callee.type === 'MemberExpression' &&
node.callee.object.type === 'NewExpression' &&
node.callee.property.type === 'Identifier' &&
node.callee.property.name === 'getTime' &&
!node.callee.computed &&
node.arguments.length === 0
) {
const replacement = getDateNowReplacement(node.callee.object);
if (replacement) {
context.report({
node,
messageId: 'preferDateNow',
fix(fixer) {
return fixer.replaceText(node, replacement);
}
});
}
}
},
// +new Date()
UnaryExpression(node: UnaryExpression) {
if (node.operator === '+' && node.argument.type === 'NewExpression') {
const replacement = getDateNowReplacement(node.argument);
if (replacement) {
context.report({
node,
messageId: 'preferDateNow',
fix(fixer) {
return fixer.replaceText(node, replacement);
}
});
}
}
}
};
}
};