Skip to content

Commit

Permalink
Switch to standard .flat()
Browse files Browse the repository at this point in the history
  • Loading branch information
mjbvz committed Apr 29, 2024
1 parent c1cc1a9 commit d418e67
Show file tree
Hide file tree
Showing 20 changed files with 85 additions and 80 deletions.
20 changes: 20 additions & 0 deletions .eslintplugin/code-no-assign-casts.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/

import * as eslint from 'eslint';

export = new class NoAssignCasts implements eslint.Rule.RuleModule {

create(context: eslint.Rule.RuleContext): eslint.Rule.RuleListener {
return {
['VariableDeclarator > TSTypeAssertion']: (node: any) => {
context.report({
node,
message: "Don't use type assertions when assigning variables as this can hide type errors. Instead use `const x: T = ...`"
});
},
};
}
};
7 changes: 0 additions & 7 deletions src/vs/base/common/arrays.ts
Original file line number Diff line number Diff line change
Expand Up @@ -435,13 +435,6 @@ export function commonPrefixLength<T>(one: ReadonlyArray<T>, other: ReadonlyArra
return result;
}

/**
* @deprecated Use `[].flat()`
*/
export function flatten<T>(arr: T[][]): T[] {
return (<T[]>[]).concat(...arr);
}

export function range(to: number): number[];
export function range(from: number, to: number): number[];
export function range(arg: number, to?: number): number[] {
Expand Down
3 changes: 1 addition & 2 deletions src/vs/workbench/common/views.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,6 @@ import { getOrSet, SetMap } from 'vs/base/common/map';
import { Registry } from 'vs/platform/registry/common/platform';
import { IKeybindings } from 'vs/platform/keybinding/common/keybindingsRegistry';
import { ExtensionIdentifier } from 'vs/platform/extensions/common/extensions';
import { flatten } from 'vs/base/common/arrays';
import { SyncDescriptor } from 'vs/platform/instantiation/common/descriptors';
import { IProgressIndicator } from 'vs/platform/progress/common/progress';
import Severity from 'vs/base/common/severity';
Expand Down Expand Up @@ -204,7 +203,7 @@ class ViewContainersRegistryImpl extends Disposable implements IViewContainersRe
private readonly defaultViewContainers: ViewContainer[] = [];

get all(): ViewContainer[] {
return flatten([...this.viewContainers.values()]);
return [...this.viewContainers.values()].flat();
}

registerViewContainer(viewContainerDescriptor: IViewContainerDescriptor, viewContainerLocation: ViewContainerLocation, options?: { isDefault?: boolean; doNotRegisterOpenCommand?: boolean }): ViewContainer {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/

import { distinct, flatten } from 'vs/base/common/arrays';
import { distinct } from 'vs/base/common/arrays';
import { sequence } from 'vs/base/common/async';
import { CancellationToken, CancellationTokenSource } from 'vs/base/common/cancellation';
import { Emitter, Event } from 'vs/base/common/event';
Expand Down Expand Up @@ -258,7 +258,7 @@ export class ConfigurationManager implements IConfigurationManager {
});

const nestedPicks = await Promise.all(picks);
const items = flatten(nestedPicks);
const items = nestedPicks.flat();

input.items = items;
input.busy = false;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -63,7 +63,6 @@ import { isVirtualWorkspace } from 'vs/platform/workspace/common/virtualWorkspac
import { escapeMarkdownSyntaxTokens, IMarkdownString, MarkdownString } from 'vs/base/common/htmlContent';
import { IPaneCompositePartService } from 'vs/workbench/services/panecomposite/browser/panecomposite';
import { ViewContainerLocation } from 'vs/workbench/common/views';
import { flatten } from 'vs/base/common/arrays';
import { fromNow } from 'vs/base/common/date';
import { IPreferencesService } from 'vs/workbench/services/preferences/common/preferences';
import { getLocale } from 'vs/platform/languagePacks/common/languagePacks';
Expand Down Expand Up @@ -251,7 +250,7 @@ export class ActionWithDropDownAction extends ExtensionAction {
private readonly actionsGroups: ExtensionAction[][],
) {
super(id, label);
this.extensionActions = flatten(actionsGroups);
this.extensionActions = actionsGroups.flat();
this.update();
this._register(Event.any(...this.extensionActions.map(a => a.onDidChange))(() => this.update(true)));
this.extensionActions.forEach(a => this._register(a));
Expand Down
10 changes: 5 additions & 5 deletions src/vs/workbench/contrib/extensions/browser/extensionsViews.ts
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ import { IConfigurationService } from 'vs/platform/configuration/common/configur
import { INotificationService, Severity } from 'vs/platform/notification/common/notification';
import { ViewPane, IViewPaneOptions, ViewPaneShowActions } from 'vs/workbench/browser/parts/views/viewPane';
import { IWorkspaceContextService } from 'vs/platform/workspace/common/workspace';
import { coalesce, distinct, flatten } from 'vs/base/common/arrays';
import { coalesce, distinct } from 'vs/base/common/arrays';
import { alert } from 'vs/base/browser/ui/aria/aria';
import { IListContextMenuEvent } from 'vs/base/browser/ui/list/list';
import { CancellationToken } from 'vs/base/common/cancellation';
Expand Down Expand Up @@ -978,12 +978,12 @@ export class ExtensionsListView extends ViewPane {
.map(extensionId => isString(extensionId) ? extensionId.toLowerCase() : extensionId);

return distinct(
flatten(await Promise.all([
(await Promise.all([
// Order is important
this.extensionRecommendationsService.getImportantRecommendations(),
this.extensionRecommendationsService.getFileBasedRecommendations(),
this.extensionRecommendationsService.getOtherRecommendations()
])).filter(extensionId => !local.includes(extensionId.toLowerCase()) && !workspaceRecommendations.includes(extensionId.toLowerCase())
])).flat().filter(extensionId => !local.includes(extensionId.toLowerCase()) && !workspaceRecommendations.includes(extensionId.toLowerCase())
), extensionId => extensionId.toLowerCase());
}

Expand All @@ -993,13 +993,13 @@ export class ExtensionsListView extends ViewPane {
const localExtensionIds = localExtensions.map(e => e.identifier.id.toLowerCase());

const allRecommendations = distinct(
flatten(await Promise.all([
(await Promise.all([
// Order is important
this.getWorkspaceRecommendations(),
this.extensionRecommendationsService.getImportantRecommendations(),
this.extensionRecommendationsService.getFileBasedRecommendations(),
this.extensionRecommendationsService.getOtherRecommendations()
])).filter(extensionId => {
])).flat().filter(extensionId => {
if (isString(extensionId)) {
return !localExtensionIds.includes(extensionId.toLowerCase());
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
*--------------------------------------------------------------------------------------------*/

import { EXTENSION_IDENTIFIER_PATTERN } from 'vs/platform/extensionManagement/common/extensionManagement';
import { distinct, equals, flatten } from 'vs/base/common/arrays';
import { distinct, equals } from 'vs/base/common/arrays';
import { ExtensionRecommendations, ExtensionRecommendation } from 'vs/workbench/contrib/extensions/browser/extensionRecommendations';
import { INotificationService } from 'vs/platform/notification/common/notification';
import { ExtensionRecommendationReason } from 'vs/workbench/services/extensionRecommendations/common/extensionRecommendations';
Expand Down Expand Up @@ -150,7 +150,7 @@ export class WorkspaceRecommendations extends ExtensionRecommendations {
const invalidExtensions: string[] = [];
let message = '';

const allRecommendations = distinct(flatten(contents.map(({ recommendations }) => recommendations || [])));
const allRecommendations = distinct(contents.flatMap(({ recommendations }) => recommendations || []));
const regEx = new RegExp(EXTENSION_IDENTIFIER_PATTERN);
for (const extensionId of allRecommendations) {
if (regEx.test(extensionId)) {
Expand Down
26 changes: 12 additions & 14 deletions src/vs/workbench/contrib/extensions/common/extensionQuery.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/

import { flatten } from 'vs/base/common/arrays';
import { EXTENSION_CATEGORIES } from 'vs/platform/extensions/common/extensions';

export class Query {
Expand All @@ -26,19 +25,18 @@ export class Query {
const hasSort = subcommands.sort.some(subcommand => queryContains(`@sort:${subcommand}`));
const hasCategory = subcommands.category.some(subcommand => queryContains(`@category:${subcommand}`));

return flatten(
commands.map(command => {
if (hasSort && command === 'sort' || hasCategory && command === 'category') {
return [];
}
if (command in subcommands) {
return (subcommands as Record<string, readonly string[]>)[command]
.map(subcommand => `@${command}:${subcommand}${subcommand === '' ? '' : ' '}`);
}
else {
return queryContains(`@${command}`) ? [] : [`@${command} `];
}
}));
return commands.flatMap(command => {
if (hasSort && command === 'sort' || hasCategory && command === 'category') {
return [];
}
if (command in subcommands) {
return (subcommands as Record<string, readonly string[]>)[command]
.map(subcommand => `@${command}:${subcommand}${subcommand === '' ? '' : ' '}`);
}
else {
return queryContains(`@${command}`) ? [] : [`@${command} `];
}
});
}

static parse(value: string): Query {
Expand Down
4 changes: 2 additions & 2 deletions src/vs/workbench/contrib/markers/browser/markersModel.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ import { basename, extUri } from 'vs/base/common/resources';
import { URI } from 'vs/base/common/uri';
import { Range, IRange } from 'vs/editor/common/core/range';
import { IMarker, MarkerSeverity, IRelatedInformation, IMarkerData } from 'vs/platform/markers/common/markers';
import { isNonEmptyArray, flatten } from 'vs/base/common/arrays';
import { isNonEmptyArray } from 'vs/base/common/arrays';
import { ResourceMap } from 'vs/base/common/map';
import { Emitter, Event } from 'vs/base/common/event';
import { Hasher } from 'vs/base/common/hash';
Expand Down Expand Up @@ -52,7 +52,7 @@ export class ResourceMarkers {

get markers(): readonly Marker[] {
if (!this._cachedMarkers) {
this._cachedMarkers = flatten([...this._markersMap.values()]).sort(ResourceMarkers._compareMarkers);
this._cachedMarkers = [...this._markersMap.values()].flat().sort(ResourceMarkers._compareMarkers);
}
return this._cachedMarkers;
}
Expand Down
3 changes: 1 addition & 2 deletions src/vs/workbench/contrib/scm/browser/scmViewPane.ts
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,6 @@ import { compareFileNames, comparePaths } from 'vs/base/common/comparers';
import { FuzzyScore, createMatches, IMatch } from 'vs/base/common/filters';
import { IViewDescriptorService, ViewContainerLocation } from 'vs/workbench/common/views';
import { localize } from 'vs/nls';
import { flatten } from 'vs/base/common/arrays';
import { IStorageService, StorageScope, StorageTarget } from 'vs/platform/storage/common/storage';
import { EditorResourceAccessor, SideBySideEditor } from 'vs/workbench/common/editor';
import { SIDE_BAR_BACKGROUND, PANEL_BACKGROUND } from 'vs/workbench/common/theme';
Expand Down Expand Up @@ -589,7 +588,7 @@ class RepositoryPaneActionRunner extends ActionRunner {
const selection = this.getSelectedResources();
const contextIsSelected = selection.some(s => s === context);
const actualContext = contextIsSelected ? selection : [context];
const args = flatten(actualContext.map(e => ResourceTree.isResourceNode(e) ? ResourceTree.collect(e) : [e]));
const args = actualContext.map(e => ResourceTree.isResourceNode(e) ? ResourceTree.collect(e) : [e]).flat();
await action.run(...args);
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/

import { coalesce, flatten } from 'vs/base/common/arrays';
import { coalesce } from 'vs/base/common/arrays';
import { URI } from 'vs/base/common/uri';
import 'vs/css!./media/searchEditor';
import { ServicesAccessor } from 'vs/editor/browser/editorExtensions';
Expand Down Expand Up @@ -255,10 +255,9 @@ export const serializeSearchResultForEditor =

const allResults =
flattenSearchResultSerializations(
flatten(
searchResult.folderMatches().sort(matchComparer)
.map(folderMatch => folderMatch.allDownstreamFileMatches().sort(matchComparer)
.flatMap(fileMatch => fileMatchToSearchResultFormat(fileMatch, labelFormatter)))));
searchResult.folderMatches().sort(matchComparer)
.map(folderMatch => folderMatch.allDownstreamFileMatches().sort(matchComparer)
.flatMap(fileMatch => fileMatchToSearchResultFormat(fileMatch, labelFormatter))).flat());

return {
matchRanges: allResults.matchRanges.map(translateRangeLines(info.length)),
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ import { Button } from 'vs/base/browser/ui/button/button';
import { renderLabelWithIcons } from 'vs/base/browser/ui/iconLabel/iconLabels';
import { DomScrollableElement } from 'vs/base/browser/ui/scrollbar/scrollableElement';
import { Toggle } from 'vs/base/browser/ui/toggle/toggle';
import { coalesce, equals, flatten } from 'vs/base/common/arrays';
import { coalesce, equals } from 'vs/base/common/arrays';
import { Delayer, Throttler } from 'vs/base/common/async';
import { CancellationToken } from 'vs/base/common/cancellation';
import { Codicon } from 'vs/base/common/codicons';
Expand Down Expand Up @@ -570,7 +570,7 @@ export class GettingStartedPage extends EditorPane {
this.updateMediaSourceForColorMode(mediaElement, media.path);

this.stepDisposables.add(addDisposableListener(this.stepMediaComponent, 'click', () => {
const hrefs = flatten(stepToExpand.description.map(lt => lt.nodes.filter((node): node is ILink => typeof node !== 'string').map(node => node.href)));
const hrefs = stepToExpand.description.map(lt => lt.nodes.filter((node): node is ILink => typeof node !== 'string').map(node => node.href)).flat();
if (hrefs.length === 1) {
const href = hrefs[0];
if (href.startsWith('http')) {
Expand Down Expand Up @@ -602,7 +602,7 @@ export class GettingStartedPage extends EditorPane {
}));

this.stepDisposables.add(addDisposableListener(this.stepMediaComponent, 'click', () => {
const hrefs = flatten(stepToExpand.description.map(lt => lt.nodes.filter((node): node is ILink => typeof node !== 'string').map(node => node.href)));
const hrefs = stepToExpand.description.map(lt => lt.nodes.filter((node): node is ILink => typeof node !== 'string').map(node => node.href)).flat();
if (hrefs.length === 1) {
const href = hrefs[0];
if (href.startsWith('http')) {
Expand Down Expand Up @@ -644,7 +644,7 @@ export class GettingStartedPage extends EditorPane {

if (serializedContextKeyExprs) {
const contextKeyExprs = coalesce(serializedContextKeyExprs.map(expr => ContextKeyExpr.deserialize(expr)));
const watchingKeys = new Set(flatten(contextKeyExprs.map(expr => expr.keys())));
const watchingKeys = new Set(contextKeyExprs.flatMap(expr => expr.keys()));

this.stepDisposables.add(this.contextService.onDidChangeContext(e => {
if (e.affectsSome(watchingKeys)) { postTrueKeysMessage(); }
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ import { ILink, LinkedText, parseLinkedText } from 'vs/base/common/linkedText';
import { walkthroughsExtensionPoint } from 'vs/workbench/contrib/welcomeGettingStarted/browser/gettingStartedExtensionPoint';
import { InstantiationType, registerSingleton } from 'vs/platform/instantiation/common/extensions';
import { dirname } from 'vs/base/common/path';
import { coalesce, flatten } from 'vs/base/common/arrays';
import { coalesce } from 'vs/base/common/arrays';
import { IViewsService } from 'vs/workbench/services/views/common/viewsService';
import { localize, localize2 } from 'vs/nls';
import { ITelemetryService } from 'vs/platform/telemetry/common/telemetry';
Expand Down Expand Up @@ -567,10 +567,10 @@ export class WalkthroughsService extends Disposable implements IWalkthroughsServ
}

if (!step.completionEvents.length) {
step.completionEvents = coalesce(flatten(
step.completionEvents = coalesce(
step.description
.filter(linkedText => linkedText.nodes.length === 1) // only buttons
.map(linkedText =>
.flatMap(linkedText =>
linkedText.nodes
.filter(((node): node is ILink => typeof node !== 'string'))
.map(({ href }) => {
Expand All @@ -581,7 +581,7 @@ export class WalkthroughsService extends Disposable implements IWalkthroughsServ
return 'onLink:' + href;
}
return undefined;
}))));
})));
}

if (!step.completionEvents.length) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
*--------------------------------------------------------------------------------------------*/

import * as glob from 'vs/base/common/glob';
import { distinct, firstOrDefault, flatten, insert } from 'vs/base/common/arrays';
import { distinct, firstOrDefault, insert } from 'vs/base/common/arrays';
import { Disposable, IDisposable, toDisposable } from 'vs/base/common/lifecycle';
import { basename, extname, isEqual } from 'vs/base/common/resources';
import { URI } from 'vs/base/common/uri';
Expand Down Expand Up @@ -339,7 +339,7 @@ export class EditorResolverService extends Disposable implements IEditorResolver
* Returns all editors as an array. Possible to contain duplicates
*/
private get _registeredEditors(): RegisteredEditors {
return flatten(Array.from(this._flattenedEditors.values()));
return Array.from(this._flattenedEditors.values()).flat();
}

updateUserAssociations(globPattern: string, editorID: string): void {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/

import { distinct, flatten } from 'vs/base/common/arrays';
import { distinct } from 'vs/base/common/arrays';
import { Emitter, Event } from 'vs/base/common/event';
import { JSONPath, parse } from 'vs/base/common/json';
import { Disposable } from 'vs/base/common/lifecycle';
Expand Down Expand Up @@ -81,12 +81,12 @@ export class WorkspaceExtensionsConfigService extends Disposable implements IWor

async getRecommendations(): Promise<string[]> {
const configs = await this.getExtensionsConfigs();
return distinct(flatten(configs.map(c => c.recommendations ? c.recommendations.map(c => c.toLowerCase()) : [])));
return distinct(configs.flatMap(c => c.recommendations ? c.recommendations.map(c => c.toLowerCase()) : []));
}

async getUnwantedRecommendations(): Promise<string[]> {
const configs = await this.getExtensionsConfigs();
return distinct(flatten(configs.map(c => c.unwantedRecommendations ? c.unwantedRecommendations.map(c => c.toLowerCase()) : [])));
return distinct(configs.flatMap(c => c.unwantedRecommendations ? c.unwantedRecommendations.map(c => c.toLowerCase()) : []));
}

async toggleRecommendation(extensionId: string): Promise<void> {
Expand Down
27 changes: 13 additions & 14 deletions src/vs/workbench/services/preferences/common/preferencesModels.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/

import { flatten, tail, coalesce } from 'vs/base/common/arrays';
import { tail, coalesce } from 'vs/base/common/arrays';
import { IStringDictionary } from 'vs/base/common/collections';
import { Emitter, Event } from 'vs/base/common/event';
import { JSONVisitor, visit } from 'vs/base/common/json';
Expand Down Expand Up @@ -900,19 +900,18 @@ export class DefaultSettingsEditorModel extends AbstractSettingsModel implements
builder.pushGroup(settingsGroup);

// builder has rewritten settings ranges, fix match ranges
const fixedMatches = flatten(
filterMatches
.map(m => m.matches || [])
.map((settingMatches, i) => {
const setting = settingsGroup.sections[0].settings[i];
return settingMatches.map(range => {
return new Range(
range.startLineNumber + setting.range.startLineNumber,
range.startColumn,
range.endLineNumber + setting.range.startLineNumber,
range.endColumn);
});
}));
const fixedMatches = filterMatches
.map(m => m.matches || [])
.flatMap((settingMatches, i) => {
const setting = settingsGroup.sections[0].settings[i];
return settingMatches.map(range => {
return new Range(
range.startLineNumber + setting.range.startLineNumber,
range.startColumn,
range.endLineNumber + setting.range.startLineNumber,
range.endColumn);
});
});

return fixedMatches;
}
Expand Down
Loading

0 comments on commit d418e67

Please sign in to comment.