Skip to content

Commit 611b77f

Browse files
committed
Migrate more places to use Map/Set
1 parent eb2f4e2 commit 611b77f

File tree

107 files changed

+631
-670
lines changed

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

107 files changed

+631
-670
lines changed

src/compiler/binder.ts

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -218,7 +218,7 @@ namespace ts {
218218
let symbolCount = 0;
219219

220220
let Symbol: new (flags: SymbolFlags, name: __String) => Symbol;
221-
let classifiableNames: UnderscoreEscapedMap<true>;
221+
let classifiableNames: Set<__String>;
222222

223223
const unreachableFlow: FlowNode = { flags: FlowFlags.Unreachable };
224224
const reportedUnreachableFlow: FlowNode = { flags: FlowFlags.Unreachable };
@@ -237,7 +237,7 @@ namespace ts {
237237
options = opts;
238238
languageVersion = getEmitScriptTarget(options);
239239
inStrictMode = bindInStrictMode(file, opts);
240-
classifiableNames = createUnderscoreEscapedMap<true>();
240+
classifiableNames = new Set();
241241
symbolCount = 0;
242242

243243
Symbol = objectAllocator.getSymbolConstructor();
@@ -445,7 +445,7 @@ namespace ts {
445445
symbol = symbolTable.get(name);
446446

447447
if (includes & SymbolFlags.Classifiable) {
448-
classifiableNames.set(name, true);
448+
classifiableNames.add(name);
449449
}
450450

451451
if (!symbol) {
@@ -1964,7 +1964,7 @@ namespace ts {
19641964
}
19651965

19661966
if (inStrictMode && !isAssignmentTarget(node)) {
1967-
const seen = createUnderscoreEscapedMap<ElementKind>();
1967+
const seen = new Map<__String, ElementKind>();
19681968

19691969
for (const prop of node.properties) {
19701970
if (prop.kind === SyntaxKind.SpreadAssignment || prop.name.kind !== SyntaxKind.Identifier) {
@@ -3142,7 +3142,7 @@ namespace ts {
31423142
bindAnonymousDeclaration(node, SymbolFlags.Class, bindingName);
31433143
// Add name of class expression into the map for semantic classifier
31443144
if (node.name) {
3145-
classifiableNames.set(node.name.escapedText, true);
3145+
classifiableNames.add(node.name.escapedText);
31463146
}
31473147
}
31483148

src/compiler/checker.ts

Lines changed: 116 additions & 114 deletions
Large diffs are not rendered by default.

src/compiler/commandLineParser.ts

Lines changed: 24 additions & 24 deletions
Original file line numberDiff line numberDiff line change
@@ -83,33 +83,33 @@ namespace ts {
8383
export const optionsForWatch: CommandLineOption[] = [
8484
{
8585
name: "watchFile",
86-
type: createMapFromTemplate({
86+
type: new Map(getEntries({
8787
fixedpollinginterval: WatchFileKind.FixedPollingInterval,
8888
prioritypollinginterval: WatchFileKind.PriorityPollingInterval,
8989
dynamicprioritypolling: WatchFileKind.DynamicPriorityPolling,
9090
usefsevents: WatchFileKind.UseFsEvents,
9191
usefseventsonparentdirectory: WatchFileKind.UseFsEventsOnParentDirectory,
92-
}),
92+
})),
9393
category: Diagnostics.Advanced_Options,
9494
description: Diagnostics.Specify_strategy_for_watching_file_Colon_FixedPollingInterval_default_PriorityPollingInterval_DynamicPriorityPolling_UseFsEvents_UseFsEventsOnParentDirectory,
9595
},
9696
{
9797
name: "watchDirectory",
98-
type: createMapFromTemplate({
98+
type: new Map(getEntries({
9999
usefsevents: WatchDirectoryKind.UseFsEvents,
100100
fixedpollinginterval: WatchDirectoryKind.FixedPollingInterval,
101101
dynamicprioritypolling: WatchDirectoryKind.DynamicPriorityPolling,
102-
}),
102+
})),
103103
category: Diagnostics.Advanced_Options,
104104
description: Diagnostics.Specify_strategy_for_watching_directory_on_platforms_that_don_t_support_recursive_watching_natively_Colon_UseFsEvents_default_FixedPollingInterval_DynamicPriorityPolling,
105105
},
106106
{
107107
name: "fallbackPolling",
108-
type: createMapFromTemplate({
108+
type: new Map(getEntries({
109109
fixedinterval: PollingWatchKind.FixedInterval,
110110
priorityinterval: PollingWatchKind.PriorityInterval,
111111
dynamicpriority: PollingWatchKind.DynamicPriority,
112-
}),
112+
})),
113113
category: Diagnostics.Advanced_Options,
114114
description: Diagnostics.Specify_strategy_for_creating_a_polling_watch_when_it_fails_to_create_using_file_system_events_Colon_FixedInterval_default_PriorityInterval_DynamicPriority,
115115
},
@@ -286,7 +286,7 @@ namespace ts {
286286
{
287287
name: "target",
288288
shortName: "t",
289-
type: createMapFromTemplate({
289+
type: new Map(getEntries({
290290
es3: ScriptTarget.ES3,
291291
es5: ScriptTarget.ES5,
292292
es6: ScriptTarget.ES2015,
@@ -297,7 +297,7 @@ namespace ts {
297297
es2019: ScriptTarget.ES2019,
298298
es2020: ScriptTarget.ES2020,
299299
esnext: ScriptTarget.ESNext,
300-
}),
300+
})),
301301
affectsSourceFile: true,
302302
affectsModuleResolution: true,
303303
affectsEmit: true,
@@ -309,7 +309,7 @@ namespace ts {
309309
{
310310
name: "module",
311311
shortName: "m",
312-
type: createMapFromTemplate({
312+
type: new Map(getEntries({
313313
none: ModuleKind.None,
314314
commonjs: ModuleKind.CommonJS,
315315
amd: ModuleKind.AMD,
@@ -319,7 +319,7 @@ namespace ts {
319319
es2015: ModuleKind.ES2015,
320320
es2020: ModuleKind.ES2020,
321321
esnext: ModuleKind.ESNext
322-
}),
322+
})),
323323
affectsModuleResolution: true,
324324
affectsEmit: true,
325325
paramType: Diagnostics.KIND,
@@ -356,11 +356,11 @@ namespace ts {
356356
},
357357
{
358358
name: "jsx",
359-
type: createMapFromTemplate({
359+
type: new Map(getEntries({
360360
"preserve": JsxEmit.Preserve,
361361
"react-native": JsxEmit.ReactNative,
362362
"react": JsxEmit.React
363-
}),
363+
})),
364364
affectsSourceFile: true,
365365
paramType: Diagnostics.KIND,
366366
showInSimplifiedHelpView: true,
@@ -476,11 +476,11 @@ namespace ts {
476476
},
477477
{
478478
name: "importsNotUsedAsValues",
479-
type: createMapFromTemplate({
479+
type: new Map(getEntries({
480480
remove: ImportsNotUsedAsValues.Remove,
481481
preserve: ImportsNotUsedAsValues.Preserve,
482482
error: ImportsNotUsedAsValues.Error
483-
}),
483+
})),
484484
affectsEmit: true,
485485
affectsSemanticDiagnostics: true,
486486
category: Diagnostics.Advanced_Options,
@@ -610,10 +610,10 @@ namespace ts {
610610
// Module Resolution
611611
{
612612
name: "moduleResolution",
613-
type: createMapFromTemplate({
613+
type: new Map(getEntries({
614614
node: ModuleResolutionKind.NodeJs,
615615
classic: ModuleResolutionKind.Classic,
616-
}),
616+
})),
617617
affectsModuleResolution: true,
618618
paramType: Diagnostics.STRATEGY,
619619
category: Diagnostics.Module_Resolution_Options,
@@ -818,10 +818,10 @@ namespace ts {
818818
},
819819
{
820820
name: "newLine",
821-
type: createMapFromTemplate({
821+
type: new Map(getEntries({
822822
crlf: NewLineKind.CarriageReturnLineFeed,
823823
lf: NewLineKind.LineFeed
824-
}),
824+
})),
825825
affectsEmit: true,
826826
paramType: Diagnostics.NEWLINE,
827827
category: Diagnostics.Advanced_Options,
@@ -1096,8 +1096,8 @@ namespace ts {
10961096

10971097
/*@internal*/
10981098
export function createOptionNameMap(optionDeclarations: readonly CommandLineOption[]): OptionsNameMap {
1099-
const optionsNameMap = createMap<CommandLineOption>();
1100-
const shortOptionNames = createMap<string>();
1099+
const optionsNameMap = new Map<string, CommandLineOption>();
1100+
const shortOptionNames = new Map<string, string>();
11011101
forEach(optionDeclarations, option => {
11021102
optionsNameMap.set(option.name.toLowerCase(), option);
11031103
if (option.shortName) {
@@ -2032,7 +2032,7 @@ namespace ts {
20322032
{ optionsNameMap }: OptionsNameMap,
20332033
pathOptions?: { configFilePath: string, useCaseSensitiveFileNames: boolean }
20342034
): Map<string, CompilerOptionsValue> {
2035-
const result = createMap<CompilerOptionsValue>();
2035+
const result = new Map<string, CompilerOptionsValue>();
20362036
const getCanonicalFileName = pathOptions && createGetCanonicalFileName(pathOptions.useCaseSensitiveFileNames);
20372037

20382038
for (const name in options) {
@@ -2962,17 +2962,17 @@ namespace ts {
29622962
// Literal file names (provided via the "files" array in tsconfig.json) are stored in a
29632963
// file map with a possibly case insensitive key. We use this map later when when including
29642964
// wildcard paths.
2965-
const literalFileMap = createMap<string>();
2965+
const literalFileMap = new Map<string, string>();
29662966

29672967
// Wildcard paths (provided via the "includes" array in tsconfig.json) are stored in a
29682968
// file map with a possibly case insensitive key. We use this map to store paths matched
29692969
// via wildcard, and to handle extension priority.
2970-
const wildcardFileMap = createMap<string>();
2970+
const wildcardFileMap = new Map<string, string>();
29712971

29722972
// Wildcard paths of json files (provided via the "includes" array in tsconfig.json) are stored in a
29732973
// file map with a possibly case insensitive key. We use this map to store paths matched
29742974
// via wildcard of *.json kind
2975-
const wildCardJsonFileMap = createMap<string>();
2975+
const wildCardJsonFileMap = new Map<string, string>();
29762976
const { filesSpecs, validatedIncludeSpecs, validatedExcludeSpecs, wildcardDirectories } = spec;
29772977

29782978
// Rather than requery this for each file and filespec, we query the supported extensions

src/compiler/core.ts

Lines changed: 37 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -40,17 +40,23 @@ namespace ts {
4040
}
4141

4242
export const emptyArray: never[] = [] as never[];
43+
export const emptyMap: ReadonlyMap<never, never> = new Map<never, never>();
44+
export const emptySet: ReadonlySet<never> = new Set<never>();
4345

44-
/** Create a new map. */
45-
export function createMap<K, V>(): Map<K, V>;
46-
export function createMap<T>(): Map<string, T>;
46+
/**
47+
* Create a new map.
48+
* @deprecated Use `new Map()` instead.
49+
*/
4750
export function createMap<K, V>(): Map<K, V> {
4851
return new Map<K, V>();
4952
}
5053

51-
/** Create a new map from a template object is provided, the map will copy entries from it. */
54+
/**
55+
* Create a new map from a template object is provided, the map will copy entries from it.
56+
* @deprecated Use `new Map(getEntries(template))` instead.
57+
*/
5258
export function createMapFromTemplate<T>(template: MapLike<T>): Map<string, T> {
53-
const map: Map<string, T> = new Map<string, T>();
59+
const map = new Map<string, T>();
5460

5561
// Copies keys/values from template. Note that for..in will not throw if
5662
// template is undefined, and instead will just exit the loop.
@@ -590,6 +596,15 @@ namespace ts {
590596
}
591597
}
592598

599+
export function getOrUpdate<K, V>(map: Map<K, V>, key: K, callback: () => V) {
600+
if (map.has(key)) {
601+
return map.get(key)!;
602+
}
603+
const value = callback();
604+
map.set(key, value);
605+
return value;
606+
}
607+
593608
export function tryAddToSet<T>(set: Set<T>, value: T) {
594609
if (!set.has(value)) {
595610
set.add(value);
@@ -1275,6 +1290,19 @@ namespace ts {
12751290
return values;
12761291
}
12771292

1293+
const _entries = Object.entries ? Object.entries : <T>(obj: MapLike<T>) => {
1294+
const keys = getOwnKeys(obj);
1295+
const result: [string, T][] = Array(keys.length);
1296+
for (const key of keys) {
1297+
result.push([key, obj[key]]);
1298+
}
1299+
return result;
1300+
};
1301+
1302+
export function getEntries<T>(obj: MapLike<T>): [string, T][] {
1303+
return obj ? _entries(obj) : [];
1304+
}
1305+
12781306
export function arrayOf<T>(count: number, f: (index: number) => T): T[] {
12791307
const result = new Array(count);
12801308
for (let i = 0; i < count; i++) {
@@ -1375,9 +1403,11 @@ namespace ts {
13751403
return result;
13761404
}
13771405

1406+
export function group<T, K>(values: readonly T[], getGroupId: (value: T) => K): readonly (readonly T[])[];
1407+
export function group<T, K, R>(values: readonly T[], getGroupId: (value: T) => K, resultSelector: (values: readonly T[]) => R): R[];
13781408
export function group<T>(values: readonly T[], getGroupId: (value: T) => string): readonly (readonly T[])[];
13791409
export function group<T, R>(values: readonly T[], getGroupId: (value: T) => string, resultSelector: (values: readonly T[]) => R): R[];
1380-
export function group<T>(values: readonly T[], getGroupId: (value: T) => string, resultSelector: (values: readonly T[]) => readonly T[] = identity): readonly (readonly T[])[] {
1410+
export function group<T, K>(values: readonly T[], getGroupId: (value: T) => K, resultSelector: (values: readonly T[]) => readonly T[] = identity): readonly (readonly T[])[] {
13811411
return arrayFrom(arrayToMultiMap(values, getGroupId).values(), resultSelector);
13821412
}
13831413

@@ -1596,7 +1626,7 @@ namespace ts {
15961626

15971627
/** A version of `memoize` that supports a single primitive argument */
15981628
export function memoizeOne<A extends string | number | boolean | undefined, T>(callback: (arg: A) => T): (arg: A) => T {
1599-
const map = createMap<T>();
1629+
const map = new Map<string, T>();
16001630
return (arg: A) => {
16011631
const key = `${typeof arg}:${arg}`;
16021632
let value = map.get(key);

src/compiler/emitter.ts

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -682,9 +682,9 @@ namespace ts {
682682

683683
function createSourceFilesFromBundleBuildInfo(bundle: BundleBuildInfo, buildInfoDirectory: string, host: EmitUsingBuildInfoHost): readonly SourceFile[] {
684684
const jsBundle = Debug.checkDefined(bundle.js);
685-
const prologueMap = jsBundle.sources?.prologues && arrayToMap(jsBundle.sources.prologues, prologueInfo => "" + prologueInfo.file);
685+
const prologueMap = jsBundle.sources?.prologues && arrayToMap(jsBundle.sources.prologues, prologueInfo => prologueInfo.file);
686686
return bundle.sourceFiles.map((fileName, index) => {
687-
const prologueInfo = prologueMap?.get("" + index);
687+
const prologueInfo = prologueMap?.get(index);
688688
const statements = prologueInfo?.directives.map(directive => {
689689
const literal = setTextRange(factory.createStringLiteral(directive.expression.text), directive.expression);
690690
const statement = setTextRange(factory.createExpressionStatement(literal), directive);
@@ -834,7 +834,7 @@ namespace ts {
834834
const extendedDiagnostics = !!printerOptions.extendedDiagnostics;
835835
const newLine = getNewLineCharacter(printerOptions);
836836
const moduleKind = getEmitModuleKind(printerOptions);
837-
const bundledHelpers = createMap<boolean>();
837+
const bundledHelpers = new Map<string, boolean>();
838838

839839
let currentSourceFile: SourceFile | undefined;
840840
let nodeIdToGeneratedName: string[]; // Map of generated names for specific nodes.
@@ -1682,7 +1682,7 @@ namespace ts {
16821682
if (moduleKind === ModuleKind.None || printerOptions.noEmitHelpers) {
16831683
return undefined;
16841684
}
1685-
const bundledHelpers = createMap<boolean>();
1685+
const bundledHelpers = new Map<string, boolean>();
16861686
for (const sourceFile of bundle.sourceFiles) {
16871687
const shouldSkip = getExternalHelpersModuleName(sourceFile) !== undefined;
16881688
const helpers = getSortedEmitHelpers(sourceFile);

src/compiler/factory/nodeFactory.ts

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -5654,7 +5654,7 @@ namespace ts {
56545654
left.splice(0, 0, ...declarations.slice(0, rightStandardPrologueEnd));
56555655
}
56565656
else {
5657-
const leftPrologues = createMap<boolean>();
5657+
const leftPrologues = new Map<string, boolean>();
56585658
for (let i = 0; i < leftStandardPrologueEnd; i++) {
56595659
const leftPrologue = statements[i] as PrologueDirective;
56605660
leftPrologues.set(leftPrologue.expression.text, true);
@@ -6159,7 +6159,7 @@ namespace ts {
61596159
): InputFiles {
61606160
const node = parseNodeFactory.createInputFiles();
61616161
if (!isString(javascriptTextOrReadFileText)) {
6162-
const cache = createMap<string | false>();
6162+
const cache = new Map<string, string | false>();
61636163
const textGetter = (path: string | undefined) => {
61646164
if (path === undefined) return undefined;
61656165
let value = cache.get(path);

src/compiler/moduleNameResolver.ts

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -482,7 +482,7 @@ namespace ts {
482482

483483
/*@internal*/
484484
export function createCacheWithRedirects<T>(options?: CompilerOptions): CacheWithRedirects<T> {
485-
let ownMap: Map<string, T> = createMap();
485+
let ownMap: Map<string, T> = new Map();
486486
const redirectsMap = new Map<Path, Map<string, T>>();
487487
return {
488488
ownMap,
@@ -509,7 +509,7 @@ namespace ts {
509509
let redirects = redirectsMap.get(path);
510510
if (!redirects) {
511511
// Reuse map if redirected reference map uses same resolution
512-
redirects = !options || optionsHaveModuleResolutionChanges(options, redirectedReference.commandLine.options) ? createMap() : ownMap;
512+
redirects = !options || optionsHaveModuleResolutionChanges(options, redirectedReference.commandLine.options) ? new Map() : ownMap;
513513
redirectsMap.set(path, redirects);
514514
}
515515
return redirects;
@@ -532,7 +532,7 @@ namespace ts {
532532

533533
function getOrCreateCacheForDirectory(directoryName: string, redirectedReference?: ResolvedProjectReference) {
534534
const path = toPath(directoryName, currentDirectory, getCanonicalFileName);
535-
return getOrCreateCache<Map<string, ResolvedModuleWithFailedLookupLocations>>(directoryToModuleNameMap, redirectedReference, path, createMap);
535+
return getOrCreateCache<Map<string, ResolvedModuleWithFailedLookupLocations>>(directoryToModuleNameMap, redirectedReference, path, () => new Map());
536536
}
537537

538538
function getOrCreateCacheForModuleName(nonRelativeModuleName: string, redirectedReference?: ResolvedProjectReference): PerModuleNameCache {
@@ -551,7 +551,7 @@ namespace ts {
551551
}
552552

553553
function createPerModuleNameCache(): PerModuleNameCache {
554-
const directoryPathMap = createMap<ResolvedModuleWithFailedLookupLocations>();
554+
const directoryPathMap = new Map<string, ResolvedModuleWithFailedLookupLocations>();
555555

556556
return { get, set };
557557

src/compiler/moduleSpecifiers.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -216,7 +216,7 @@ namespace ts.moduleSpecifiers {
216216
function getAllModulePaths(importingFileName: string, importedFileName: string, host: ModuleSpecifierResolutionHost): readonly string[] {
217217
const cwd = host.getCurrentDirectory();
218218
const getCanonicalFileName = hostGetCanonicalFileName(host);
219-
const allFileNames = createMap<string>();
219+
const allFileNames = new Map<string, string>();
220220
let importedFileFromNodeModules = false;
221221
forEachFileNameOfModule(
222222
importingFileName,

0 commit comments

Comments
 (0)