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 consistent-date-clone rule #2544

Merged
merged 7 commits into from
Jan 30, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
22 changes: 22 additions & 0 deletions docs/rules/consistent-date-clone.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
# Prefer passing `Date` directly to the constructor when cloning

💼 This rule is enabled in the ✅ `recommended` [config](https://github.com/sindresorhus/eslint-plugin-unicorn#preset-configs-eslintconfigjs).

🔧 This rule is automatically fixable by the [`--fix` CLI option](https://eslint.org/docs/latest/user-guide/command-line-interface#--fix).

<!-- end auto-generated rule header -->
<!-- Do not manually modify this header. Run: `npm run fix:eslint-docs` -->

The [`Date` constructor](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/Date) can clone a `⁠Date` object directly when passed as an argument, making timestamp conversion unnecessary.

> Note: Before ES2015, `new Date(date)` converted `date` to a string first, so it's not safe to clone.

## Examples

```js
// ❌
new Date(date.getTime());

// ✅
new Date(date);
```
1 change: 1 addition & 0 deletions readme.md
Original file line number Diff line number Diff line change
Expand Up @@ -59,6 +59,7 @@ export default [
| [better-regex](docs/rules/better-regex.md) | Improve regexes by making them shorter, consistent, and safer. | | 🔧 | |
| [catch-error-name](docs/rules/catch-error-name.md) | Enforce a specific parameter name in catch clauses. | ✅ | 🔧 | |
| [consistent-assert](docs/rules/consistent-assert.md) | Enforce consistent assertion style with `node:assert`. | ✅ | 🔧 | |
| [consistent-date-clone](docs/rules/consistent-date-clone.md) | Prefer passing `Date` directly to the constructor when cloning. | ✅ | 🔧 | |
| [consistent-destructuring](docs/rules/consistent-destructuring.md) | Use destructured variables over properties. | | 🔧 | 💡 |
| [consistent-empty-array-spread](docs/rules/consistent-empty-array-spread.md) | Prefer consistent types when spreading a ternary in an array literal. | ✅ | 🔧 | |
| [consistent-existence-index-check](docs/rules/consistent-existence-index-check.md) | Enforce consistent style for element existence checks with `indexOf()`, `lastIndexOf()`, `findIndex()`, and `findLastIndex()`. | ✅ | 🔧 | |
Expand Down
50 changes: 50 additions & 0 deletions rules/consistent-date-clone.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
import {isMethodCall, isNewExpression} from './ast/index.js';
import {removeMethodCall} from './fix/index.js';

const MESSAGE_ID_ERROR = 'consistent-date-clone/error';
const messages = {
[MESSAGE_ID_ERROR]: 'Unnecessary `.getTime()` call.',
};

/** @param {import('eslint').Rule.RuleContext} context */
const create = context => ({
NewExpression(newExpression) {
if (!isNewExpression(newExpression, {name: 'Date', argumentsLength: 1})) {
return;
}

const [callExpression] = newExpression.arguments;

if (!isMethodCall(callExpression, {
method: 'getTime',
argumentsLength: 0,
optionalCall: false,
optionalMember: false,
})) {
return;
}

return {
node: callExpression,
loc: {start: callExpression.callee.property.loc.start, end: callExpression.loc.end},
messageId: MESSAGE_ID_ERROR,
fix: fixer => removeMethodCall(fixer, callExpression, context.sourceCode),
};
},
});

/** @type {import('eslint').Rule.RuleModule} */
const config = {
create,
meta: {
type: 'suggestion',
docs: {
description: 'Prefer passing `Date` directly to the constructor when cloning.',
recommended: true,
},
fixable: 'code',
messages,
},
};

export default config;
2 changes: 2 additions & 0 deletions rules/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import {createRule} from './utils/rule.js';
import betterRegex from './better-regex.js';
import catchErrorName from './catch-error-name.js';
import consistentAssert from './consistent-assert.js';
import consistentDateClone from './consistent-date-clone.js';
import consistentDestructuring from './consistent-destructuring.js';
import consistentEmptyArraySpread from './consistent-empty-array-spread.js';
import consistentExistenceIndexCheck from './consistent-existence-index-check.js';
Expand Down Expand Up @@ -132,6 +133,7 @@ const rules = {
'better-regex': createRule(betterRegex, 'better-regex'),
'catch-error-name': createRule(catchErrorName, 'catch-error-name'),
'consistent-assert': createRule(consistentAssert, 'consistent-assert'),
'consistent-date-clone': createRule(consistentDateClone, 'consistent-date-clone'),
'consistent-destructuring': createRule(consistentDestructuring, 'consistent-destructuring'),
'consistent-empty-array-spread': createRule(consistentEmptyArraySpread, 'consistent-empty-array-spread'),
'consistent-existence-index-check': createRule(consistentExistenceIndexCheck, 'consistent-existence-index-check'),
Expand Down
49 changes: 49 additions & 0 deletions test/consistent-date-clone.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
import outdent from 'outdent';
import {getTester} from './utils/test.js';

const {test} = getTester(import.meta);

test.snapshot({
valid: [
'new Date(date)',
'date.getTime()',
'new Date(...date.getTime())',
'new Date(getTime())',
'new Date(date.getTime(), extraArgument)',
'new Date(date.not_getTime())',
'new Date(date?.getTime())',
'new NotDate(date.getTime())',
'new Date(date[getTime]())',
'new Date(date.getTime(extraArgument))',
'Date(date.getTime())',
// We may support these cases in future, https://github.com/sindresorhus/eslint-plugin-unicorn/issues/2437
outdent`
new Date(
date.getFullYear(),
date.getMonth(),
date.getDate(),
date.getHours(),
date.getMinutes(),
date.getSeconds(),
date.getMilliseconds(),
);
`,
outdent`
new Date(
date.getFullYear(),
date.getMonth(),
date.getDate(),
date.getHours(),
date.getMinutes(),
date.getSeconds(),
);
`,
],
invalid: [
'new Date(date.getTime())',
'new Date(date.getTime(),)',
'new Date((0, date).getTime())',
'new Date(date.getTime(/* comment */))',
'new Date(date./* comment */getTime())',
],
});
1 change: 1 addition & 0 deletions test/package.js
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,7 @@ const RULES_WITHOUT_PASS_FAIL_SECTIONS = new Set([
'no-named-default',
'consistent-assert',
'no-accessor-recursion',
'consistent-date-clone',
]);

test('Every rule is defined in index file in alphabetical order', t => {
Expand Down
110 changes: 110 additions & 0 deletions test/snapshots/consistent-date-clone.js.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,110 @@
# Snapshot report for `test/consistent-date-clone.js`

The actual snapshot is saved in `consistent-date-clone.js.snap`.

Generated by [AVA](https://avajs.dev).

## invalid(1): new Date(date.getTime())

> Input

`␊
1 | new Date(date.getTime())␊
`

> Output

`␊
1 | new Date(date)␊
`

> Error 1/1

`␊
> 1 | new Date(date.getTime())␊
| ^^^^^^^^^ Unnecessary \`.getTime()\` call.␊
`

## invalid(2): new Date(date.getTime(),)

> Input

`␊
1 | new Date(date.getTime(),)␊
`

> Output

`␊
1 | new Date(date,)␊
`

> Error 1/1

`␊
> 1 | new Date(date.getTime(),)␊
| ^^^^^^^^^ Unnecessary \`.getTime()\` call.␊
`

## invalid(3): new Date((0, date).getTime())

> Input

`␊
1 | new Date((0, date).getTime())␊
`

> Output

`␊
1 | new Date((0, date))␊
`

> Error 1/1

`␊
> 1 | new Date((0, date).getTime())␊
| ^^^^^^^^^ Unnecessary \`.getTime()\` call.␊
`

## invalid(4): new Date(date.getTime(/* comment */))

> Input

`␊
1 | new Date(date.getTime(/* comment */))␊
`

> Output

`␊
1 | new Date(date)␊
`

> Error 1/1

`␊
> 1 | new Date(date.getTime(/* comment */))␊
| ^^^^^^^^^^^^^^^^^^^^^^ Unnecessary \`.getTime()\` call.␊
`

## invalid(5): new Date(date./* comment */getTime())

> Input

`␊
1 | new Date(date./* comment */getTime())␊
`

> Output

`␊
1 | new Date(date)␊
`

> Error 1/1

`␊
> 1 | new Date(date./* comment */getTime())␊
| ^^^^^^^^^ Unnecessary \`.getTime()\` call.␊
`
Binary file added test/snapshots/consistent-date-clone.js.snap
Binary file not shown.
Loading