Skip to content

chore: enable unicorn/prefer-spread #9834

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

Merged
merged 7 commits into from
Sep 4, 2024
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
1 change: 1 addition & 0 deletions eslint.config.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -332,6 +332,7 @@ export default tseslint.config(
'unicorn/prefer-export-from': 'error',
'unicorn/prefer-node-protocol': 'error',
'unicorn/prefer-regexp-test': 'error',
'unicorn/prefer-spread': 'error',
'unicorn/prefer-string-replace-all': 'error',
'unicorn/prefer-structured-clone': 'error',
},
Expand Down
12 changes: 4 additions & 8 deletions packages/ast-spec/tests/fixtures.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -339,16 +339,12 @@ describe('AST Fixtures', () => {

// once we've run all the tests, snapshot the list of fixtures that have differences for easy reference
it('List fixtures with AST differences', () => {
expect(
Array.from(fixturesWithASTDifferences).sort(),
).toMatchSpecificSnapshot(
expect([...fixturesWithASTDifferences].sort()).toMatchSpecificSnapshot(
path.resolve(__dirname, 'fixtures-with-differences-ast.shot'),
);
});
it('List fixtures with Token differences', () => {
expect(
Array.from(fixturesWithTokenDifferences).sort(),
).toMatchSpecificSnapshot(
expect([...fixturesWithTokenDifferences].sort()).toMatchSpecificSnapshot(
path.resolve(__dirname, 'fixtures-with-differences-tokens.shot'),
);
});
Expand All @@ -357,7 +353,7 @@ describe('AST Fixtures', () => {
Object.fromEntries(
Object.entries(fixturesWithErrorDifferences).map(([key, value]) => [
key,
Array.from(value).sort(),
[...value].sort(),
]),
),
).toMatchSpecificSnapshot(
Expand All @@ -366,7 +362,7 @@ describe('AST Fixtures', () => {
});
it('List fixtures we expect babel to not support', () => {
expect(
Array.from(fixturesConfiguredToExpectBabelToNotSupport).sort(),
[...fixturesConfiguredToExpectBabelToNotSupport].sort(),
).toMatchSpecificSnapshot(
path.resolve(__dirname, 'fixtures-without-babel-support.shot'),
);
Expand Down
2 changes: 1 addition & 1 deletion packages/ast-spec/tests/util/serializers/Node.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ function sortKeys<Node extends TSESTree.Node>(
keySet.delete('interpreter');
}

return Array.from(keySet).sort((a, b) =>
return [...keySet].sort((a, b) =>
a.localeCompare(b),
) as (keyof typeof node)[];
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -291,7 +291,7 @@ function* fixSeparateNamedExports(
): IterableIterator<TSESLint.RuleFix> {
const { node, typeBasedSpecifiers, inlineTypeSpecifiers, valueSpecifiers } =
report;
const typeSpecifiers = typeBasedSpecifiers.concat(inlineTypeSpecifiers);
const typeSpecifiers = [...typeBasedSpecifiers, ...inlineTypeSpecifiers];
const source = getSourceFromExport(node);
const specifierNames = typeSpecifiers.map(getSpecifierText).join(', ');

Expand Down
2 changes: 1 addition & 1 deletion packages/eslint-plugin/src/rules/member-ordering.ts
Original file line number Diff line number Diff line change
Expand Up @@ -509,7 +509,7 @@ function getRankOrder(
orderConfig: MemberType[],
): number {
let rank = -1;
const stack = memberGroups.slice(); // Get a copy of the member groups
const stack = [...memberGroups]; // Get a copy of the member groups

while (stack.length > 0 && rank === -1) {
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
Expand Down
2 changes: 1 addition & 1 deletion packages/eslint-plugin/src/rules/no-shadow.ts
Original file line number Diff line number Diff line change
Expand Up @@ -645,7 +645,7 @@ export default createRule<Options, MessageIds>({
return {
'Program:exit'(node): void {
const globalScope = context.sourceCode.getScope(node);
const stack = globalScope.childScopes.slice();
const stack = [...globalScope.childScopes];

while (stack.length) {
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
Expand Down
7 changes: 4 additions & 3 deletions packages/eslint-plugin/src/rules/prefer-function-type.ts
Original file line number Diff line number Diff line change
Expand Up @@ -108,9 +108,10 @@ export default createRule({
const text = context.sourceCode
.getText()
.slice(start, member.range[1]);
const comments = context.sourceCode
.getCommentsBefore(member)
.concat(context.sourceCode.getCommentsAfter(member));
const comments = [
...context.sourceCode.getCommentsBefore(member),
...context.sourceCode.getCommentsAfter(member),
];
let suggestion = `${text.slice(0, colonPos)} =>${text.slice(
colonPos + 1,
)}`;
Expand Down
4 changes: 2 additions & 2 deletions packages/eslint-plugin/src/rules/prefer-readonly.ts
Original file line number Diff line number Diff line change
Expand Up @@ -460,8 +460,8 @@ class ClassScope {
});

return [
...Array.from(this.privateModifiableMembers.values()),
...Array.from(this.privateModifiableStatics.values()),
...this.privateModifiableMembers.values(),
...this.privateModifiableStatics.values(),
];
}
}
2 changes: 1 addition & 1 deletion packages/eslint-plugin/src/rules/unified-signatures.ts
Original file line number Diff line number Diff line change
Expand Up @@ -515,7 +515,7 @@ export default createRule<Options, MessageIds>({
'checkScope() called without a current scope',
);
const failures = checkOverloads(
Array.from(scope.overloads.values()),
[...scope.overloads.values()],
scope.typeParameters,
);
addFailures(failures);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,7 @@ export function generateType(schema: JSONSchema4, refMap: RefMap): AST {
throw new UnexpectedError(
`Could not find definition for $ref ${
schema.$ref
}.\nAvailable refs:\n${Array.from(refMap.keys()).join('\n')})`,
}.\nAvailable refs:\n${[...refMap.keys()].join('\n')})`,
schema,
);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,7 @@ export function optimizeAST(ast: AST | null): void {
for (const element of elements) {
uniqueElementsMap.set(JSON.stringify(element), element);
}
const uniqueElements = Array.from(uniqueElementsMap.values());
const uniqueElements = [...uniqueElementsMap.values()];

// @ts-expect-error -- purposely overwriting the property with a flattened list
ast.elements = uniqueElements;
Expand Down
2 changes: 1 addition & 1 deletion packages/rule-schema-to-typescript-types/src/printAST.ts
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,7 @@ function printAST(ast: AST): CodeWithComments {
const code = printAndMaybeParenthesise(ast.elementType);
return {
code: `${code.code}[]`,
commentLines: ast.commentLines.concat(code.commentLines),
commentLines: [...ast.commentLines, ...code.commentLines],
};
}

Expand Down
2 changes: 1 addition & 1 deletion packages/rule-tester/src/utils/flat-config-schema.ts
Original file line number Diff line number Diff line change
Expand Up @@ -122,7 +122,7 @@ function normalizeRuleOptions(
ruleOptions: SharedConfig.RuleLevel | SharedConfig.RuleLevelAndOptions,
): SharedConfig.RuleLevelAndOptions {
const finalOptions = Array.isArray(ruleOptions)
? ruleOptions.slice(0)
? [...ruleOptions]
: [ruleOptions];

finalOptions[0] = ruleSeverities.get(
Expand Down
2 changes: 1 addition & 1 deletion packages/scope-manager/src/ScopeManager.ts
Original file line number Diff line number Diff line change
Expand Up @@ -56,7 +56,7 @@ class ScopeManager {
scope.childScopes.forEach(recurse);
}
this.scopes.forEach(recurse);
return Array.from(variables).sort((a, b) => a.$id - b.$id);
return [...variables].sort((a, b) => a.$id - b.$id);
}

constructor(options: ScopeManagerOptions) {
Expand Down
2 changes: 1 addition & 1 deletion packages/scope-manager/tests/fixtures.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -125,7 +125,7 @@ function nestDescribe(

if (type[1] && !type[1].has(value)) {
throw new Error(
`Expected value for ${key} to be one of (${Array.from(type[1]).join(
`Expected value for ${key} to be one of (${[...type[1]].join(
' | ',
)}), but got ${value as string}`,
);
Expand Down
8 changes: 4 additions & 4 deletions packages/typescript-estree/src/convert.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1984,9 +1984,9 @@
);
break;
case SyntaxKind.NamedImports:
result.specifiers = result.specifiers.concat(
node.importClause.namedBindings.elements.map(el =>
this.convertChild(el),
result.specifiers.push(

Check warning on line 1987 in packages/typescript-estree/src/convert.ts

View check run for this annotation

Codecov / codecov/patch

packages/typescript-estree/src/convert.ts#L1987

Added line #L1987 was not covered by tests
...node.importClause.namedBindings.elements.map(
el => this.convertChild(el) as TSESTree.ImportClause,

Check warning on line 1989 in packages/typescript-estree/src/convert.ts

View check run for this annotation

Codecov / codecov/patch

packages/typescript-estree/src/convert.ts#L1989

Added line #L1989 was not covered by tests
),
);
break;
Expand Down Expand Up @@ -2165,7 +2165,7 @@
left.type === AST_NODE_TYPES.SequenceExpression &&
node.left.kind !== SyntaxKind.ParenthesizedExpression
) {
result.expressions = result.expressions.concat(left.expressions);
result.expressions.push(...left.expressions);

Check warning on line 2168 in packages/typescript-estree/src/convert.ts

View check run for this annotation

Codecov / codecov/patch

packages/typescript-estree/src/convert.ts#L2168

Added line #L2168 was not covered by tests
} else {
result.expressions.push(left);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@ function getErrorStart(
describedFilePath: string,
parseSettings: ParseSettings,
): string {
const relativeProjects = Array.from(parseSettings.projects.values()).map(
const relativeProjects = [...parseSettings.projects.values()].map(
projectFile => describeFilePath(projectFile, parseSettings.tsconfigRootDir),
);

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -320,7 +320,7 @@ function createWatchProgram(
path,
!extensions
? undefined
: extensions.concat(parseSettings.extraFileExtensions),
: [...extensions, ...parseSettings.extraFileExtensions],
exclude,
include,
depth,
Expand Down
4 changes: 2 additions & 2 deletions packages/typescript-estree/src/getModifiers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ export function getModifiers(
if (includeIllegalModifiers || ts.canHaveModifiers(node)) {
// eslint-disable-next-line @typescript-eslint/no-deprecated -- this is safe as it's guarded
const modifiers = ts.getModifiers(node as ts.HasModifiers);
return modifiers ? Array.from(modifiers) : undefined;
return modifiers ? [...modifiers] : undefined;
}

return undefined;
Expand All @@ -44,7 +44,7 @@ export function getDecorators(
if (includeIllegalDecorators || ts.canHaveDecorators(node)) {
// eslint-disable-next-line @typescript-eslint/no-deprecated -- this is safe as it's guarded
const decorators = ts.getDecorators(node as ts.HasDecorators);
return decorators ? Array.from(decorators) : undefined;
return decorators ? [...decorators] : undefined;
}

return undefined;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -103,14 +103,12 @@ export function resolveProjectList(
}

const uniqueCanonicalProjectPaths = new Map(
nonGlobProjects
.concat(globProjectPaths)
.map(project => [
getCanonicalFileName(
ensureAbsolutePath(project, options.tsconfigRootDir),
),
[...nonGlobProjects, ...globProjectPaths].map(project => [
getCanonicalFileName(
ensureAbsolutePath(project, options.tsconfigRootDir),
]),
),
ensureAbsolutePath(project, options.tsconfigRootDir),
]),
);

log(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -16,9 +16,7 @@ const SUPPORTED_PRERELEASE_RANGES: string[] = [];
const ACTIVE_TYPESCRIPT_VERSION = ts.version;
const isRunningSupportedTypeScriptVersion = semver.satisfies(
ACTIVE_TYPESCRIPT_VERSION,
[SUPPORTED_TYPESCRIPT_VERSIONS]
.concat(SUPPORTED_PRERELEASE_RANGES)
.join(' || '),
[SUPPORTED_TYPESCRIPT_VERSIONS, ...SUPPORTED_PRERELEASE_RANGES].join(' || '),
);

let warnedAboutTSVersion = false;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -87,7 +87,7 @@ function openClientFileFromProjectService(
serviceSettings.maximumDefaultProjectFileMatchCount
) {
const filePrintLimit = 20;
const filesToPrint = Array.from(defaultProjectMatchedFiles).slice(
const filesToPrint = [...defaultProjectMatchedFiles].slice(
0,
filePrintLimit,
);
Expand Down
4 changes: 2 additions & 2 deletions packages/utils/src/eslint-utils/deepMerge.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,10 +20,10 @@ export function deepMerge(
second: ObjectLike = {},
): Record<string, unknown> {
// get the unique set of keys across both objects
const keys = new Set(Object.keys(first).concat(Object.keys(second)));
const keys = new Set([...Object.keys(first), ...Object.keys(second)]);

return Object.fromEntries(
Array.from(keys, key => {
[...keys].map(key => {
const firstHasKey = key in first;
const secondHasKey = key in second;
const firstValue = first[key];
Expand Down
12 changes: 4 additions & 8 deletions packages/website-eslint/src/mock/path.js
Original file line number Diff line number Diff line change
Expand Up @@ -167,14 +167,10 @@ export function relative(from, to) {
}
}

let outputParts = [];
for (let i = samePartsLength; i < fromParts.length; i++) {
outputParts.push('..');
}

outputParts = outputParts.concat(toParts.slice(samePartsLength));

return outputParts.join('/');
return [
...Array(fromParts.length - samePartsLength).fill('..'),
...toParts.slice(samePartsLength),
].join('/');
}

export const sep = '/';
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,7 @@ function ConfigTypeScript(props: ConfigTypeScriptProps): React.JSX.Element {
key: item.name,
type: 'string',
label: item.description.message,
enum: ['', ...Array.from<string>(item.type.keys())],
enum: ['', ...item.type.keys()],
});
}
return group;
Expand Down
2 changes: 1 addition & 1 deletion packages/website/src/components/editor/LoadedEditor.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -155,7 +155,7 @@ export const LoadedEditor: React.FC<LoadedEditorProps> = ({
enableSchemaRequest: false,
allowComments: true,
schemas: [
...Array.from(webLinter.rules.values()).map(rule => ({
...[...webLinter.rules.values()].map(rule => ({
uri: createRuleUri(rule.name),
schema: getRuleJsonSchemaWithErrorLevel(rule.name, rule.schema),
})),
Expand Down
11 changes: 7 additions & 4 deletions packages/website/src/components/editor/useSandboxServices.ts
Original file line number Diff line number Diff line change
Expand Up @@ -120,10 +120,13 @@ export const useSandboxServices = (
);

onLoaded(
Array.from(webLinter.rules.values()),
Array.from(
new Set([...sandboxInstance.supportedVersions, window.ts.version]),
)
[...webLinter.rules.values()],
[
...new Set([
...sandboxInstance.supportedVersions,
window.ts.version,
]),
]
.filter(item =>
semverSatisfies(item, rootPackageJson.devDependencies.typescript),
)
Expand Down
4 changes: 2 additions & 2 deletions packages/website/src/components/lib/jsonSchema.ts
Original file line number Diff line number Diff line change
Expand Up @@ -189,15 +189,15 @@ export function getTypescriptJsonSchema(): JSONSchema4 {
value = {
description: item.description.message,
items: {
enum: Array.from(item.element.type.keys()),
enum: [...item.element.type.keys()],
type: 'string',
},
type: 'array',
};
} else if (item.type instanceof Map) {
value = {
description: item.description.message,
enum: Array.from(item.type.keys()),
enum: [...item.type.keys()],
type: 'string',
};
}
Expand Down
2 changes: 1 addition & 1 deletion packages/website/src/components/linter/createLinter.ts
Original file line number Diff line number Diff line change
Expand Up @@ -182,7 +182,7 @@ export function createLinter(
applyTSConfig('/tsconfig.json');

return {
configs: Array.from(configs.keys()),
configs: [...configs.keys()],
onLint: onLint.register,
onParse: onParse.register,
rules,
Expand Down
2 changes: 1 addition & 1 deletion packages/website/src/components/linter/createParser.ts
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ export function createParser(
): tsvfs.VirtualTypeScriptEnvironment => {
return vfs.createVirtualTypeScriptEnvironment(
system,
Array.from(registeredFiles),
[...registeredFiles],
window.ts,
compilerOptions,
);
Expand Down
2 changes: 1 addition & 1 deletion packages/website/src/theme/NotFound/Content/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ export default function NotFound(): React.JSX.Element {
<h1 className={styles.title}>
<div className={styles.code}>$ npx eslint .</div>
<strong>
{`'${location.pathname}'`.split('').map((letter, i) => (
{[...`'${location.pathname}'`].map((letter, i) => (
<span className={styles.word} key={i}>
{letter}
</span>
Expand Down
6 changes: 2 additions & 4 deletions tools/scripts/generate-lib.mts
Original file line number Diff line number Diff line change
Expand Up @@ -237,7 +237,7 @@ async function main(): Promise<void> {

if (requiredBaseImports.size > 0) {
imports.push(
`import {${Array.from(requiredBaseImports)
`import {${[...requiredBaseImports]
.sort()
.join(',')}} from './${BASE_CONFIG_MODULE_NAME}';`,
);
Expand Down Expand Up @@ -288,9 +288,7 @@ async function main(): Promise<void> {
// generate a string union type for the lib names

const libUnionCode = [
`type Lib = ${Array.from(libMap.keys())
.map(k => `'${k}'`)
.join(' | ')};`,
`type Lib = ${[...libMap.keys()].map(k => `'${k}'`).join(' | ')};`,
'',
'export { Lib };',
];
Expand Down
Loading